如何在contextmenu的CommandParameter中传递TreeView项的selectedItem

时间:2017-02-20 05:54:11

标签: mvvm treeview

我在xaml以下到树视图控件与上下文菜单“编辑”。当我选择编辑上下文菜单时,我的EditCommand方法在MVVM中执行。

问题:

我将参数作为“TreeView”。我想获得参数作为选定的项目(使用人民币)

 <TreeView x:Name="treeView" ItemsSource="{Binding TreeViewItems}">
   <TreeView.ContextMenu>
     <ContextMenu>
         <MenuItem Header="Edit" Command="{Binding EditCommand}" 
              CommandParameter="{Binding PlacementTarget, RelativeSource={RelativeSource FindAncestor,AncestorType={x:Type ContextMenu}}}"/>
     </ContextMenu>
  </TreeView.ContextMenu>
</TreeView>

任何人都可以指导我在CommandParameter中更改内容以获取Selected Item。

我已尝试过以下链接,但提供的解决方案对我不起作用。 [WPF treeview contextmenu command parameter [CommandParameters in ContextMenu in WPF

1 个答案:

答案 0 :(得分:1)

只需将SelectedItem添加到PlacementTarget,就像这样:

<TreeView x:Name="treeView" ItemsSource="{Binding TreeViewItems}">
   <TreeView.ContextMenu>
      <ContextMenu>
          <MenuItem Header="Edit" Command="{Binding EditCommand}" 
              CommandParameter="{Binding PlacementTarget.SelectedItem, RelativeSource={RelativeSource FindAncestor,AncestorType={x:Type ContextMenu}}}"/>
      </ContextMenu>
   </TreeView.ContextMenu>
</TreeView>

更新1

ICommand实施:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;

namespace WpfApplication1
{
  public class Command<T> : ICommand
  {
    private Action<T> _execute;
    private Predicate<T> _canExecute;

    public event EventHandler CanExecuteChanged
    {
        add { CommandManager.RequerySuggested += value; }
        remove { CommandManager.RequerySuggested -= value; }
    }

    public Command(Action<T> execute, Predicate<T> canExecute = null)
    {
        _execute = execute;
        _canExecute = canExecute;
    }
    public bool CanExecute(object parameter)
    {
        if (_canExecute == null) return true;
        return _canExecute((T)parameter);
    }

    public void Execute(object parameter)
    {
        _execute((T)parameter);
    }
  }
}

代码背后:

using System.Collections.Generic;
using System.Windows;
using System.Linq;
using System;
using System.Collections.ObjectModel;
using System.Windows.Input;
using WpfApplication1;

namespace WPF_Sandbox
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public ObservableCollection<string> Data { get; set; }  = new ObservableCollection<string>();
        public MainWindow()
        {
            InitializeComponent();
            DataContext = this;
            Data.Add("A");
            Data.Add("B");
            Data.Add("C");
        }

        public ICommand EditCommand
        {
            get
            {
                return new Command<object>(Edit);
            }
        }

        private void Edit(object param)
        {
            //Your code here
        }
    }    
}

这适合我。