我有TreeView,其中包含不同的项目类型。项目样式通过自定义的ItemContainerStyleSelector属性定义。WPF中的上下文菜单继承
我的样式都是共享基础样式,并且每种样式中只定义了特定项目的样式。它看起来像这样:
<Style x:Key="BaseStyle" TargetType="{x:Type TreeViewItem}">
...
</Style>
<Style x:Key ="SomeSpecificStyle" TargetType="{x:Type TreeViewItem}" BasedOn="{StaticResource BaseStyle}">
<Setter Property="ContextMenu" Value="{StaticResource NodeContextMenu}"/>
...
</Style>
<Style x:Key ="SomeSpecificStyle" TargetType="{x:Type TreeViewItem}" BasedOn="{StaticResource BaseStyle}">
<Setter Property="ContextMenu" Value="{StaticResource AnotherNodeContextMenu}"/>
...
</Style>
上下文菜单中这样定义
<ContextMenu x:Key="NodeContextMenu">
<MenuItem Header="Select Views" Command="{Binding Path=OpenViewsCommand}" />
...other specific entries
<MenuItem Header="Remove" Command="{Binding Path=DocumentRemoveCommand}" />
...other entries common for all menus
</ContextMenu>
另一个上下文菜单中还应该包含像删除这些常见的物品。每当命令属性等发生更改时,都需要通过复制粘贴复制这些内容。地狱的可维护性。有没有办法定义一个包含常用项目的上下文菜单,然后“派生”特定的上下文菜单?
编辑:我发现从这个线程提示的解决方案: 我定义了一个集合与普通的物品,并定义菜单时使用复合集合包括新项目和公共项目集合
<CompositeCollection x:Key="CommonItems">
<MenuItem Header="Remove" Command="{Binding Path=DocumentRemoveCommand}">
....Other common stuff
</CompositeCollection>
<ContextMenu x:Key="NodeContextMenu">
<ContextMenu.ItemsSource>
<CompositeCollection>
<MenuItem Header="Select Views" Command="{Binding Path=OpenViewsCommand}" />
<CollectionContainer Collection="{StaticResource CommonItems}" />
</CompositeCollection>
</ContextMenu.ItemsSource>
</ContextMenu>
最好是你发布你自己的答案与编辑你的问题的答案。 – LarsTech