如何将命令绑定到 MenuItem (WPF)?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13826504/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do you bind a command to a MenuItem (WPF)?
提问by Hymanson Dean Goodwin
Here is my code from the View.xaml.cs:
这是我来自 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();
}
And here is some code from my View.xaml:
这是我的 View.xaml 中的一些代码:
<Window.ContextMenu>
<ContextMenu>
<MenuItem Name="menuItem_Close" Header="Close" Command="{Binding CloseCommand}" />
</ContextMenu>
</Window.ContextMenu>
When I run the program and select the close menu item, nothing happens. The CloseCommand code doesn't even get executed.
当我运行程序并选择关闭菜单项时,没有任何反应。CloseCommand 代码甚至不会被执行。
回答by LPL
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
:
ContextMenu
不是 VisualTree 的一部分,这就是为什么它DataContext
不会被继承。这ContextMenu.PlacementTarget
是某种继电器来获得Window
:
<MenuItem Name="menuItem_Close" Header="Close"
Command="{Binding Path=PlacementTarget.DataContext.CloseCommand, RelativeSource={RelativeSource AncestorType=ContextMenu}}" />
回答by SnakE
Old question, new answer. For me the problem was that GalaSoft.MvvmLight.Command.RelayCommand
didn't support closures for the action. RelayCommand stores a weak reference to the action so a closure gets deallocated almost immediately. The action must be a model method or be retained in some other way.
老问题,新答案。对我来说,问题是GalaSoft.MvvmLight.Command.RelayCommand
不支持关闭操作。RelayCommand 存储对动作的弱引用,因此闭包几乎立即被释放。操作必须是模型方法或以其他方式保留。
回答by user2024396
for binding cross visual tree, refer to
绑定交叉可视化树,参考
Binding Visibility for DataGridColumn in WPF
or jsut try search BindingProxy
或 jsut 尝试搜索 BindingProxy