Reputation: 14902
For a second there I was proud that I finally managed to add a ContextMenu
to a leaf in my TreeView
, but then I realized it pops up on the wrong node.
My XAML:
<TreeView
Grid.Row="1"
Grid.Column="0"
x:Name="TvShowsTreeView"
ItemsSource="{Binding TvShows}"
SelectedItemChanged="TvShowsTreeViewOnSelectedItemChanged">
<!-- Season template -->
<TreeView.ItemTemplate>
<HierarchicalDataTemplate ItemsSource="{Binding Seasons}">
<TextBlock Text="{Binding Name}">
<TextBlock.ContextMenu>
<ContextMenu>
<MenuItem Header="Hide"></MenuItem>
</ContextMenu>
</TextBlock.ContextMenu>
</TextBlock>
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
</TreeView>
When I run this, I get a context menu on the TvShows
, not on the Seasons
.
I am close, right? :) Who can help me further here?
Upvotes: 0
Views: 7661
Reputation: 14902
The correct XAML should be like this:
<TreeView
Grid.Row="1"
Grid.Column="0"
x:Name="TvShowsTreeView"
ItemsSource="{Binding TvShows}"
SelectedItemChanged="TvShowsTreeViewOnSelectedItemChanged">
<!-- TvShows template -->
<TreeView.ItemTemplate>
<HierarchicalDataTemplate ItemsSource="{Binding Seasons}">
<TextBlock Text="{Binding Name}" />
<!-- Seasons template -->
<HierarchicalDataTemplate.ItemTemplate>
<HierarchicalDataTemplate>
<TextBlock Text="{Binding Name}">
<TextBlock.ContextMenu>
<ContextMenu>
<MenuItem Header="Hide"></MenuItem>
</ContextMenu>
</TextBlock.ContextMenu>
</TextBlock>
</HierarchicalDataTemplate>
</HierarchicalDataTemplate.ItemTemplate>
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
</TreeView>
The additional HierarchicalDataTemplate specifies the template for Seasons, which itself does not need to bind ItemSource because it does not contain nodes.
Upvotes: 3