如何从ItemTemplate中将Command绑定到ContextMenu?

我想将某个命令绑定到menuItem 。 所述菜单项是在ItemTemplate内定义的ContextMenu一部分。

现在,我编译并运行,但命令永远不会被调用。 在过去,我使用了类似的模式将命令挂钩到ItemTemplate定义的按钮并成功。

任何人都知道我怎么能做到这一点?

XAML:

                   

C#:

 using System; using System.Collections.Generic; using System.Windows; using System.Windows.Data; using System.Windows.Input; namespace Wpf_treeView { public partial class MainWindow : Window { private static readonly Random rnd = new Random(); private List m_InfoData = new List(); public ListCollectionView DataInfosView { get; private set; } public static readonly DependencyProperty AddChildProperty = DependencyProperty.Register("AddChildCmd", typeof(ICommand), typeof(MainWindow)); public ICommand AddChildCmd { get { return (ICommand) GetValue(AddChildProperty); } set { SetValue(AddChildProperty, value); } } public MainWindow() { AddChildCmd = new RoutedCommand(); CommandManager.RegisterClassCommandBinding( GetType(), new CommandBinding(AddChildCmd, AddChild)); m_InfoData.Add(new InfoData(4)); m_InfoData.Add(new InfoData(1)); m_InfoData.Add(new InfoData(5)); m_InfoData[1].Children.Add(new InfoData(3)); m_InfoData[1].Children[0].Children.Add(new InfoData(7)); DataInfosView = new ListCollectionView(m_InfoData); DataContext = this; InitializeComponent(); } private void AddChild(object sender, RoutedEventArgs e) { ExecutedRoutedEventArgs args = (ExecutedRoutedEventArgs)e; InfoData info = (InfoData)args.Parameter; info.Children.Add(new InfoData(rnd.Next(0, 11))); } } class InfoData : INotifyPropertyChanged { private int infoValue; public int InfoValue { get { return infoValue; } set { if (value != infoValue) { infoValue = value; OnPropertyChanged(); } } } public List Children { get; private set; } public InfoData(int infoValue) { InfoValue = infoValue; Children = new List(); } public event PropertyChangedEventHandler PropertyChanged; protected virtual void OnPropertyChanged( [CallerMemberName] string propertyName = null) { if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } } 

好吧这应该工作:

         

ContextMenu在常规Visual Tree中不存在,因此您无法走到树上以进入主数据上下文。 通过使用Tag,您可以将主窗口的数据上下文“传入”上下文菜单。 有关与上下文菜单绑定的更多信息,请参阅此答案以及此答案 ,因为它们提供了一些有关正在发生的事情的良好解释