Создайте контекстное меню WPF для TreeView, используя HierarchicalDataTemplates - PullRequest
0 голосов
/ 26 апреля 2018

Следующий код создает TreeView, как показано ниже. Когда вы щелкаете правой кнопкой мыши по любому из дочерних узлов (не по родителям), я хотел бы отобразить простое контекстное меню.

enter image description here

Вот код, который я использую для создания древовидного представления. Мне нужно использовать HierarchicalDataTemplate, поэтому решение должно включать это.

XAML

<Window x:Class="WpfApp1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApp1"
        mc:Ignorable="d">
    <Grid>
        <TreeView ItemsSource="{Binding Parents}">
            <TreeView.Resources>
                <HierarchicalDataTemplate DataType="{x:Type local:Parent}" 
                                          ItemsSource="{Binding Children}">
                        <TextBlock Text="{Binding Name}" />
                </HierarchicalDataTemplate>
                <HierarchicalDataTemplate DataType="{x:Type local:Child}">
                    <TextBlock Text="{Binding Name}" />
                </HierarchicalDataTemplate>
            </TreeView.Resources>
        </TreeView>
    </Grid>
</Window>

КОД

using System.Collections.Generic;
using System.Windows;

namespace WpfApp1
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            DataContext = new ViewModel();
        }
    }

    public class ViewModel
    {
        public ViewModel()
        {
            Parents = new List<Parent>();

            Parents.Add(new Parent()
            {
                Name = "Parent A",
                Children = new List<Child>() {
                        new Child() { Name = "Child A" },
                        new Child() { Name = "Child B" }
                    }
            });

            Parents.Add(new Parent()
            {
                Name = "Parent B",
                Children = new List<Child>() {
                        new Child() { Name = "Child C" },
                        new Child() { Name = "Child D" }
                    }
            });
        }

        public List<Parent> Parents { get; set; }
    }

    public class Parent
    {
        public Parent() { Children = new List<Child>(); }

        public string Name { get; set; }
        public List<Child> Children { get; set; }
    }

    public class Child
    {
        public string Name { get; set; }
    }
}

ОБРАЗЕЦ ОБРАЗЦОВ КОНТЕКСТА

<ContextMenu x:Key ="ArchiveFaxNodePopupMenu">
    <MenuItem Header="Delete" />
</ContextMenu>

Спасибо за помощь!


UPDATE

Вот обновленный XAML, который заставляет меню контента работать только для дочерних типов узлов (спасибо @EdPlunket за ответ)

<Window x:Class="WpfApp1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApp1"
        mc:Ignorable="d">
    <Grid>
        <TreeView ItemsSource="{Binding Parents}">
            <TreeView.Resources>
                <HierarchicalDataTemplate DataType="{x:Type local:Parent}" 
                                          ItemsSource="{Binding Children}">
                        <TextBlock Text="{Binding Name}" />
                </HierarchicalDataTemplate>
                <HierarchicalDataTemplate DataType="{x:Type local:Child}">
                    <TextBlock Text="{Binding Name}">
                        <TextBlock.Resources>
                            <ContextMenu x:Key ="ArchiveFaxNodePopupMenu">
                                <MenuItem Header="Delete" />
                            </ContextMenu>
                        </TextBlock.Resources>
                        <TextBlock.Style>
                            <Style TargetType="TextBlock">
                                <Setter Property="ContextMenu" Value="{StaticResource ArchiveFaxNodePopupMenu}" />
                            </Style>
                        </TextBlock.Style>
                    </TextBlock>
                </HierarchicalDataTemplate>
            </TreeView.Resources>
        </TreeView>
    </Grid>
</Window>

1 Ответ

0 голосов
/ 26 апреля 2018

Это должно сделать это.

<TreeView ItemsSource="{Binding Parents}">
    <TreeView.ItemContainerStyle>
        <Style TargetType="TreeViewItem">
            <Setter Property="ContextMenu" Value="{StaticResource ArchiveFaxNodePopupMenu}" />
        </Style>
    </TreeView.ItemContainerStyle>

    <!-- resources etc. -->

Если вам нужны разные контекстные меню для разных типов элементов, поместите их в TextBlocks в шаблонах.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...