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();
}
And here is some code from my 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代码甚至没有被执行。
3 个解决方案
#1
8
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。快捷菜单。定位目标是某种获得窗口的继电器:
<MenuItem Name="menuItem_Close" Header="Close"
Command="{Binding Path=PlacementTarget.DataContext.CloseCommand, RelativeSource={RelativeSource AncestorType=ContextMenu}}" />
#2
0
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存储对操作的弱引用,以便闭包几乎立即被释放。操作必须是一个模型方法,或者以其他方式保留。
#3
-1
for binding cross visual tree, refer to
对于绑定跨视觉树,请参阅
Binding Visibility for DataGridColumn in WPF
WPF中的DataGridColumn的绑定可见性
or jsut try search BindingProxy
或者jsut尝试搜索BindingProxy
#1
8
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。快捷菜单。定位目标是某种获得窗口的继电器:
<MenuItem Name="menuItem_Close" Header="Close"
Command="{Binding Path=PlacementTarget.DataContext.CloseCommand, RelativeSource={RelativeSource AncestorType=ContextMenu}}" />
#2
0
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存储对操作的弱引用,以便闭包几乎立即被释放。操作必须是一个模型方法,或者以其他方式保留。
#3
-1
for binding cross visual tree, refer to
对于绑定跨视觉树,请参阅
Binding Visibility for DataGridColumn in WPF
WPF中的DataGridColumn的绑定可见性
or jsut try search BindingProxy
或者jsut尝试搜索BindingProxy