wpf XAML Treeviewitem 的上下文菜单(按不同属性区分)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1398943/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Context Menu for XAML Treeviewitem (Distinguished by different attributes)
提问by Mr. T.
In XAML, how do you define a context menu for treeviewitems that are distinguished by different attributes?
在 XAML 中,如何为通过不同属性区分的树视图项定义上下文菜单?
回答by Mr. T.
XAML
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
C-夏普
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;
}
}
回答by Thomas Levesque
You could define the ContextMenu
s in several styles and select the style using a ItemContainerStyleSelector
, based on those attributes.
您可以ContextMenu
在多种样式中定义s 并ItemContainerStyleSelector
根据这些属性使用 a 选择样式。
Or you could directly specify an ItemContainerStyle
and select the appropriate ContextMenu
using triggers
或者您可以直接指定一个ItemContainerStyle
并选择适当的ContextMenu
使用触发器
回答by Denis Mandrov
<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>