Context Menu for XAML Treeviewitem (Distinguished by different attributes)
Asked Answered
S

3

26

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

Strobila answered 9/9, 2009 at 10:52 Comment(0)
S
38

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;
    }
}
Strobila answered 15/9, 2009 at 10:16 Comment(3)
Sometimes it is just easier to do it in code rather than xaml. I'm not a purest and this works well. Thanks Mr T.Robot
Right clicking does not select the node.Appendicle
@Appendicle #592873Beverlee
D
16
<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>
Devora answered 21/11, 2012 at 10:26 Comment(0)
T
15

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

Trinitrotoluene answered 14/9, 2009 at 13:28 Comment(1)
Sounds like a better approach. Need to still learn styles. Thanks.Strobila

© 2022 - 2024 — McMap. All rights reserved.