3

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

1 回答 1

4

您可以将项目声明为资源并引用它们:

<Some.Resources>
    <MenuItem x:Key="mi_SelectViews" x:Shared="false"
              Header="Select Views" Command="{Binding Path=OpenViewsCommand}" />
    <MenuItem x:Key="mi_Remove" x:Shared="false"
              Header="Remove" Command="{Binding Path=DocumentRemoveCommand}" />
</Some.Resources>
<ContextMenu x:Key="NodeContextMenu">
  <StaticResource ResourceKey="mi_SelectViews" />
  ...other specific entries
  <StaticResource ResourceKey="mi_Remove" />
  ...other entries common for all menus
</ContextMenu>

x:Shared很重要)


另一种可能性是MenuItems通过对象模型方法生成,您只需将其绑定ItemsSource到一些对 a 的功能建模的对象列表MenuItem(即子项、标题和命令的属性),然后您可以创建一个Remove模型,该模型可以是其中的一部分多个列表。

于 2011-11-22T13:26:21.320 回答