如何将命令绑定到 MenuItem (WPF)? [英] How do you bind a command to a MenuItem (WPF)?
本文介绍了如何将命令绑定到 MenuItem (WPF)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我在 View.xaml.cs 中的代码:
Here is my code from the View.xaml.cs:
private RelayCommand _closeCommand;
public ICommand CloseCommand
{
get
{
if (_closeCommand == null)
{
_closeCommand = new RelayCommand(param => this.OnClose());
}
return _closeCommand;
}
}
public void OnClose()
{
Close();
}
这是我的 View.xaml 中的一些代码:
And here is some code from my View.xaml:
<Window.ContextMenu>
<ContextMenu>
<MenuItem Name="menuItem_Close" Header="Close" Command="{Binding CloseCommand}" />
</ContextMenu>
</Window.ContextMenu>
当我运行程序并选择关闭菜单项时,什么也没有发生.CloseCommand 代码甚至没有被执行.
When I run the program and select the close menu item, nothing happens. The CloseCommand code doesn't even get executed.
推荐答案
ContextMenu
不是 VisualTree 的一部分,这就是 DataContext
不会被继承的原因.这里 ContextMenu.PlacementTarget
是获取 Window
的某种中继:
ContextMenu
is not part of the VisualTree, that's why the DataContext
will not be inherited. Here ContextMenu.PlacementTarget
is some kind of relay to get the Window
:
<MenuItem Name="menuItem_Close" Header="Close"
Command="{Binding Path=PlacementTarget.DataContext.CloseCommand, RelativeSource={RelativeSource AncestorType=ContextMenu}}" />
这篇关于如何将命令绑定到 MenuItem (WPF)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文