1
votes

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>
1
How are you constructing the tree? by using HierarchicalDataTemplate? post your current XAML. - Federico Berasategui
@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 :) - bas

1 Answers

3
votes

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.