How do you bind a command to a MenuItem (WPF)?
30,679
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}}" />
Author by
Jackson Dean Goodwin
Updated on July 29, 2022Comments
-
Jackson Dean Goodwin almost 2 years
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.
-
McGarnagle over 11 yearsAre you sure it doesn't get the
DataContext
? In my test it seems to be inheriting the DataContext as you would expect ... -
Jackson Dean Goodwin over 11 yearsI tried your code for the Command="..." but it did not work - just as before - nothing happed.
-
LPL over 11 years@dbaseman According to this Popup creates its own visualtree. This means no DataContext inheritance for ContextMenu which is placed in a Popup.
-
LPL over 11 years@JacksonDeanGoodwin Any binding errors? Are you sure that DataContext is set for Window? Maybe try a Button with your Command binding in Window directly for that.
-
Agent007 over 10 yearsThanks for this. How should I bind a
static ICommand
to a MenuItem not using a ViewModel binding? I am currently using (which is not working)Command="{x:Static ...}"
but that doesn't seem to work with the solution you have provided here. Please help.