我有包含不同项目类型的 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>