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。 の機能をモデル化するオブジェクトのリストMenuItem(つまり、子アイテム、ヘッダー、およびコマンドのプロパティ) にバインドするだけで、そのRemove一部となる 1 つのモデルを作成できます。複数のリスト。

于 2011-11-22T13:26:21.320 に答える