XAML Treeviewitem的上下文菜单(由不同的属性区分)

时间:2009-09-09 10:53:00

标签: wpf xaml contextmenu treeviewitem

在XAML中,如何为不同属性区分的treeviewitems定义上下文菜单?

3 个答案:

答案 0 :(得分:31)

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-尖锐

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;
    }
}

答案 1 :(得分:15)

您可以在多种样式中定义ContextMenu,并根据这些属性使用ItemContainerStyleSelector选择样式。

或者您可以直接指定ItemContainerStyle并使用触发器选择合适的ContextMenu

答案 2 :(得分:13)

<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>