さまざまな項目タイプを含む 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>