将上下文菜单添加到TreeView WPF中的叶节点 [英] Adding context menu to leaf node in TreeView WPF

查看:65
本文介绍了将上下文菜单添加到TreeView WPF中的叶节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在WPF应用程序中,我想在 ViewModel 中向我的 TreeView 控制。这是我添加 TreeView 控件的方式。

In my WPF application, I want to add a context menu and its handler in ViewModel to the leaf nodes of my TreeView control. Here is how I have added the TreeView Control.

<TreeView Name="treePads" ItemsSource="{Binding pads}" Width="190">
    <TreeView.Resources>
        <HierarchicalDataTemplate DataType="{x:Type self:Pad}" ItemsSource="{Binding Members}">
            <StackPanel Orientation="Horizontal">
                <TextBlock Text="{Binding Name}" />
                <TextBlock Text=" [" Foreground="Blue" />
                <TextBlock Text="{Binding Members.Count}" Foreground="Blue" />
                <TextBlock Text="]" Foreground="Blue" />
            </StackPanel>
        </HierarchicalDataTemplate>

        <DataTemplate DataType="{x:Type self:PadInfo}">
            <StackPanel Orientation="Horizontal">
                <TextBlock Text="["></TextBlock>
                <TextBlock Text="{Binding SlotID}" />
                <TextBlock Text="] ["></TextBlock>
                <TextBlock Text="{Binding WellID}" />
                <TextBlock Text="]"></TextBlock>
            </StackPanel>
        </DataTemplate>
    </TreeView.Resources>
</TreeView>

下面是这段代码的输出:

Here is how the output of this code looks like:

我要添加 ContextMenu 有两个选项:重命名删除并添加 ViewModel 有事件处理程序。我怎样才能做到这一点?

I want to add a ContextMenu having two options: Rename, Delete and add there event handlers to the ViewModel. How can I do that?

推荐答案

这是有关 TreeView

http://www.codeproject.com/Articles/26288/Simplifying-the-WPF-TreeView-by-Using-the-ViewMode

共享了一个具有重命名上下文菜单的示例应用程序。该示例应帮助您解决问题。

Below I have shared a sample app which has a Rename Context Menu. The sample should help you to fix your problem.

XAML:

<TreeView Name="treeView">
    <TreeView.ItemContainerStyle>
        <Style TargetType="{x:Type TreeViewItem}">
            <!--<Setter Property="IsExpanded" Value="{Binding IsExpanded, Mode=TwoWay}" />
            <Setter Property="IsSelected" Value="{Binding IsSelected, Mode=TwoWay}" />-->
            <Setter Property="FontWeight" Value="Normal" />
            <Setter Property="ContextMenu">
                <Setter.Value>
                    <ContextMenu>

                            <MenuItem Header="Rename" Command="{Binding RenameCommand}"/>
                    </ContextMenu>
                </Setter.Value>
            </Setter>
            <Style.Triggers>
                <Trigger Property="IsSelected" Value="True">
                    <Setter Property="FontWeight" Value="Bold" />
                </Trigger>
            </Style.Triggers>

        </Style>
    </TreeView.ItemContainerStyle>
    <TreeView.ItemTemplate>
        <HierarchicalDataTemplate ItemsSource="{Binding SubElements}">
            <StackPanel Orientation="Horizontal">
                <!--<Image Margin="2" Source="{Binding ImageLocation}" Height="30" Width="30"/>-->
                <TextBlock Margin="2" Text="{Binding HeaderText}" ></TextBlock>
            </StackPanel>
        </HierarchicalDataTemplate>
    </TreeView.ItemTemplate>
</TreeView>

后面的代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Diagnostics;

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

            List<TreeViewElement> elements = new List<TreeViewElement>();
            TreeViewElement mainElement = new TreeViewElement() { ImageLocation = "Images/1.png", HeaderText = "MainElement1" };
            mainElement.SubElements = new List<TreeViewElement>();
            mainElement.SubElements.Add(new TreeViewElement() { ImageLocation = "Images/2.png", HeaderText = "SubElement1" });
            mainElement.SubElements.Add(new TreeViewElement() { ImageLocation = "Images/2.png", HeaderText = "SubElement2", BackgroundColor = "Blue" });
            elements.Add(mainElement);
            TreeViewElement mainElement2 = new TreeViewElement() { HeaderText = "MainElement2" };
            elements.Add(mainElement2);
            this.treeView.ItemsSource = elements;
        }
    }

    public class TreeViewElement
    {
        public string ImageLocation { get; set; }
        public string HeaderText { get; set; }
        public string BackgroundColor { get; set; }
        public List<TreeViewElement> SubElements { get; set; }

        private ICommand _RenameCommand;

        public ICommand RenameCommand
        {
            get {
                if (_RenameCommand == null)
                {
                    _RenameCommand = new RelayCommand((o) =>
                        {
                            // Your logic should go here
                            MessageBox.Show("HeaderText is  " +HeaderText);
                        });
                }
                return _RenameCommand; }
        }

    }

    public class RelayCommand : ICommand
    {
        #region Fields
        readonly Action<object> _execute;
        readonly Predicate<object> _canExecute;
        #endregion // Fields

        #region Constructors
        public RelayCommand(Action<object> execute)
            : this(execute, null)
        {
        }
        public RelayCommand(Action<object> execute, Predicate<object> canExecute)
        {
            if (execute == null)
                throw new ArgumentNullException("execute");

            _execute = execute;
            _canExecute = canExecute;
        }
        #endregion // Constructors
        #region ICommand Members
        [DebuggerStepThrough]
        public bool CanExecute(object parameter)
        {
            return _canExecute == null ? true : _canExecute(parameter);
        }
        public event EventHandler CanExecuteChanged
        {
            add { CommandManager.RequerySuggested += value; }
            remove { CommandManager.RequerySuggested -= value; }
        }
        public void Execute(object parameter)
        {
            _execute(parameter);
        }

        #endregion // ICommand Members
    }
}

这篇关于将上下文菜单添加到TreeView WPF中的叶节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆