wpf - Menú contextual para XAML Treeviewitem(Distinguido por diferentes atributos)
contextmenu (3)
En XAML, ¿cómo se define un menú contextual para treeviewitems que se distinguen por diferentes atributos?
XAML
<TreeView Name="SolutionTree" BorderThickness="0" SelectedItemChanged="SolutionTree_SelectedItemChanged" >
<TreeView.Resources>
<ContextMenu x:Key ="SolutionContext" StaysOpen="true">
<MenuItem Header="Add..." Click="AddFilesToFolder_Click"/>
<MenuItem Header="Rename"/>
</ContextMenu>
<ContextMenu x:Key="FolderContext" StaysOpen="true">
<MenuItem Header="Add..." Click="AddFilesToFolder_Click"/>
<MenuItem Header="Rename"/>
<MenuItem Header="Remove"/>
<Separator/>
<MenuItem Header="Copy"/>
<MenuItem Header="Cut"/>
<MenuItem Header="Paste"/>
<MenuItem Header="Move"/>
</ContextMenu>
</TreeView.Resources>
</TreeView>
C-sharp
private void SolutionTree_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
{
TreeViewItem SelectedItem = SolutionTree.SelectedItem as TreeViewItem;
switch (SelectedItem.Tag.ToString())
{
case "Solution":
SolutionTree.ContextMenu = SolutionTree.Resources["SolutionContext"] as System.Windows.Controls.ContextMenu;
break;
case "Folder":
SolutionTree.ContextMenu = SolutionTree.Resources["FolderContext"] as System.Windows.Controls.ContextMenu;
break;
}
}
Puede definir los ContextMenu
en varios estilos y seleccionar el estilo usando un ItemContainerStyleSelector
, basado en esos atributos.
O bien, puede especificar directamente un ItemContainerStyle
y seleccionar el ContextMenu
apropiado usando desencadenadores
<TreeView>
<TreeView.Resources>
<ContextMenu x:Key="ScaleCollectionPopup">
<MenuItem Header="New Scale..."/>
</ContextMenu>
<ContextMenu x:Key="ScaleItemPopup">
<MenuItem Header="Remove Scale"/>
</ContextMenu>
</TreeView.Resources>
<TreeViewItem Header="Scales" ItemsSource="{Binding Scales}" ContextMenu="{StaticResource ScaleCollectionPopup}">
<TreeViewItem.ItemContainerStyle>
<Style TargetType="{x:Type TreeViewItem}">
<Setter Property="ContextMenu" Value="{StaticResource ScaleItemPopup}"/>
</Style>
</TreeViewItem.ItemContainerStyle>
</TreeViewItem>
</TreeView>