当前位置: 首页 > 编程语言 > C#

如何从ItemTemplate绑定Command到ContextMenu?Share

时间:2023-04-10 23:37:36 C#

如何从ItemTemplate绑定Command到ContextMenu?我想将某个命令绑定到menuItem。菜单项是ItemTemplate中定义的ContextMenu的一部分。现在,我编译并运行,但从未调用该命令。过去,我曾使用类似的模式成功地将命令挂接到ItemTemplate定义的按钮。任何人都知道我怎么能做到这一点?XAML:C#:usingSystem;使用System.Collections.Generic;使用System.Windows;使用System.Windows.Data;使用System.Windows.Input;namespaceWpf_treeView{publicpartialclassMainWindow:Window{privatestaticreadonlyRandomrnd=newRandom();私有列表m_InfoData=newList();公共ListCollectionViewDataInfosView{得到;私有集;}publicstaticreadonlyDependencyPropertyAddChildProperty=DependencyProperty.Register("AddChildCmd",typeof(ICommand),typeof(MainWindow));公共ICommandAddChildCmd{get{返回(ICommand)GetValue(AddChildProperty);}set{SetValue(AddChildProperty,value);}}publicMainWindow(){AddChildCmd=newRoutedCommand();CommandManager.RegisterClassCommandBinding(GetType(),newCommandBinding(AddChildCmd,AddChild));m_InfoData.Add(新信息数据(4));m_InfoData.Add(新信息数据(1));m_InfoData.Add(新信息数据(5));m_InfoData[1].Children.Add(新InfoD阿塔(3));m_InfoData[1].Children[0].Children.Add(newInfoData(7));DataInfosView=newListCollectionView(m_InfoData);数据上下文=这个;初始化组件();}privatevoidAddChild(objectsender,RoutedEventArgse){ExecutedRoutedEventArgsargs=(ExecutedRoutedEventArgs)e;InfoDatainfo=(InfoData)args.Parameter;info.Children.Add(newInfoData(rnd.Next(0,11)));}}类信息数据:INotifyPropertyChanged{privateintinfoValue;publicintInfoValue{get{返回infoValue;}set{if(value!=infoValue){infoValue=value;OnPropertyChanged();}}}publicListChildren{get;私有集;}publicInfoData(intinfoValue){InfoValue=infoValue;孩子=新名单();}公共事件PropertyChangedEventHandlerPropertyChanged;protectedvirtualvoidOnPropertyChanged([CallerMemberName]stringpropertyName=null){if(PropertyChanged!=null)PropertyChanged(this,newPropertyChangedEventArgs(propertyName));}}}好吧这应该工作:常规可视化树中不存在ContextMenu,因此您无法沿着树向上走以到达主数据上下文通过使用Tag,您可以将主窗口的数据上下文“传递”到上下文菜单。有关绑定到上下文菜单的更多信息,请参阅此答案和此答案,因为它们对发生的情况提供了一些很好的解释以上是C#学习教程:HowtobindaCommandtoaContextMenufromanItemTemplate?如果所有分享的内容对你有用,需要进一步了解C#学习教程,希望大家多多关注。本文收集自网络,不代表立场。如涉及侵权,请点击右侧联系管理员删除。如需转载请注明出处: