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.
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}}" />
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With