Context Menu for XAML Treeviewitem (Distinguished by different attributes)

我是研究僧i 提交于 2019-12-03 10:57:14

问题


In XAML, how do you define a context menu for treeviewitems that are distinguished by different attributes?


回答1:


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



回答2:


You could define the ContextMenus in several styles and select the style using a ItemContainerStyleSelector, based on those attributes.

Or you could directly specify an ItemContainerStyle and select the appropriate ContextMenu using triggers




回答3:


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


来源:https://stackoverflow.com/questions/1398943/context-menu-for-xaml-treeviewitem-distinguished-by-different-attributes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!