简体   繁体   中英

Adding context menu to tree view by XAML only

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>

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM