我有一个TreeView,其中包含不同类型的项目。项目样式是通过自定义ItemContainerStyleSelector属性定义的。
我的样式都共享一个基本样式,每个样式中只定义了特定于项目的内容。它看起来像这样:
<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>