1

Trying to add a context menu to a TreeView with just xaml code.

  • Tv Show
    • Season 1
    • Season n

The context menu should only show when I right click a Season node.

Is that possible? I know how to solve it with code behind, but I'd like to learn to use WPF as it is intended. I have trouble finding out if I should be able to solve this with using only xaml.

Current xaml:

 <TreeView Grid.Row="1" Grid.Column="0" ItemsSource="{Binding TvShows}" x:Name="TvShowsTreeView" SelectedItemChanged="TvShowsTreeViewOnSelectedItemChanged"> <TreeView.ItemTemplate> <HierarchicalDataTemplate DataType="tvShows:TvShow" ItemsSource="{Binding Seasons}"> <TextBlock Text="{Binding Name}" /> </HierarchicalDataTemplate> </TreeView.ItemTemplate> </TreeView> 
2
  • How are you constructing the tree? by using HierarchicalDataTemplate? post your current XAML. Commented Nov 28, 2013 at 20:01
  • @HighCore, added xaml. Also have some "try" with the context menu, but it didn't lead to much yet, so I left it out for now, hoping on something that does make sense from SO :) Commented Nov 28, 2013 at 20:08

1 Answer 1

3

Try using the ItemTemplate property of HierarchicalDataTemplate. It should look like this:

 <HierarchicalDataTemplate DataType="tvShows:TvShow" ItemsSource="{Binding Seasons}"> <TextBlock Text="{Binding Name}" /> <HierarchicalDataTemplate.ItemTemplate> <DataTemplate DataType="TypeOfSeasonInYourApplication"> <TextBlock Text="{Binding Name}"> <TextBlock.ContextMenu> <ContextMenu> <!-- Place MenuItems here --> </ContextMenu> </TextBlock.ContextMenu> </TextBlock> </DataTemplate> </HierarchicalDataTemplate.ItemTemplate> </HierarchicalDataTemplate> 

I actually didn't test that myself so please let me know if that works or not.

Sign up to request clarification or add additional context in comments.

2 Comments

Nope, not quite: Property 'VisualTree' does not support values of type 'DataTemplate'.
Hmm, strange, that used to work in my case. By the error message you wrote I can only advice you to doublecheck if you placed DataTemplate inside of ItemTemplate property and not in HierarchicalDataTemplate itself (that wouldn't work for sure).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.