c# - Wpf 中菜单项的选择性样式

标签 c# wpf xaml wpf-controls wpf-style

我有一个 MenuItem,标题下有几个动态列表。我想对来自 CollectionContainer 项的项进行样式设置,而不是对已经属于 MenuItem 类型的 header 进行样式设置。我之前曾使用 DataTemplate 执行此操作,但遇到了 this issue .

<MenuItem Header="Test">
    <MenuItem.ItemsSource>
        <CompositeCollection>
            <MenuItem Header="List A" IsEnabled="False" />
            <CollectionContainer Collection="{Binding Source={StaticResource ListACollectionViewSource}}" />
            <MenuItem Header="List B" IsEnabled="False" />
            <CollectionContainer Collection="{Binding Source={StaticResource ListBCollectionViewSource}}" />
        </CompositeCollection>
    </MenuItem.ItemsSource>
</MenuItem>

如何仅设置那些特定列表的样式?

最佳答案

一种解决方案是为 MenuItems 设置默认样式,然后生成的项目将使用该样式。然后,对于非生成的项目,您可以显式地将样式设置为其他样式。

<!-- this will be the style of each generated MenuItem -->
<Style TargetType="{x:Type MenuItem}" BasedOn="{StaticResource {x:Type MenuItem}}">
  <Setter Property="Header" Value="{Binding Path=Text, StringFormat=Example {0}}" />
  <Setter Property="Command" Value="{Binding Path=Command}" />
  <Setter Property="Icon" Value="{StaticResource TheImage}" />
</Style>

它变得有点冗长,但它允许混合动态和非动态项目:

<Menu DockPanel.Dock="Top">
  <Menu.ItemTemplate>
    <HierarchicalDataTemplate DataType="{x:Type local:MenuItemViewModel}" ItemsSource="{Binding Path=MenuItems}">
      <TextBlock Text="{Binding}"/>
    </HierarchicalDataTemplate>
  </Menu.ItemTemplate>
  <Menu.ItemsSource>
    <CompositeCollection>
      <MenuItem Header="123" Style="{StaticResource NormalMenuItem}">
        <MenuItem Header="Beta1" Style="{StaticResource NormalMenuItem}"/>
        <MenuItem Header="Beta2"  Style="{StaticResource NormalMenuItem}"/>
        <MenuItem Header="Beta3"  Style="{StaticResource NormalMenuItem}"/>
        <MenuItem Header="Close" Command="Close" CommandTarget="{Binding ElementName=Window}" />
      </MenuItem>
      <CollectionContainer Collection="{Binding Source={StaticResource Items}}" />
    </CompositeCollection>
  </Menu.ItemsSource>
</Menu>

关于c# - Wpf 中菜单项的选择性样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35931000/

相关文章:

wpf - 数据网格复制同时保留字符串结构

WPF itemscontrol 子对齐

c# - WPF 设计器代码一直告诉我有错误

c# - 在.NET Core应用程序中使用NEST在ElasticSearch中的正确索引路径内进行批量收集

c# - 类成员枚举线程安全吗?

c# - 将字符串数组转换为int

c# - 如何使用 WPF 效果模仿 OuterGlowBitmapEffect?

c# - MvvmCross 未安装

wpf - 绑定(bind)到 ColumnDefinition.ActualWidth 返回 0

c# - 如何通过 ViewModel 控制 View VisualState