In trying to bind a Command
to a MenuItem
in my program, I've found that Commands
don't work with MenuItems
like they do with other controls. I've been using this post as a guide, but have had no luck so far. Basically my goal is to run a Command
when the MenuItem
is clicked.
This is my xaml after looking at the previously mentioned post. My Command
is called CreateFiles
:
<MenuItem Header="{DynamicResource save}" Command="{Binding Path=PlacementTarget.DataContext.CreateFiles, RelativeSource={RelativeSource AncestorType=ContextMenu}}" />
My Command
is created in the window's ViewModel and is declared like normal, but I will post it anyway:
private ICommand _createFiles;
public MainWindowViewModel()
{
_createFiles = new Command(createFiles_Operations);
}
public ICommand CreateFiles { get { return _createFiles; } }
private void createFiles_Operations()
{
}
To test whether or not my Command
is working I set a break point right at the first bracer. So far the program has not stopped at this break point when the MenuItem
is clicked.
Since this method does not seem to work, what can I do to make Commands
work with MenuItems
?
Update: Command
changed to ICommand
Update 2: ContextMenu
& Button
xaml:
<Button Click="Button_Click_1" Margin="5,4,0,0" Name="Button_1" Height="55" VerticalAlignment="Top" HorizontalAlignment="Left" Width="55" BorderBrush="Black">...
<ContextMenu x:Name="MainContextMenu" MouseLeave="ContextMenuMouseLeave" Background="White" BorderBrush="#FF959595" SnapsToDevicePixels="False">...
You need to set Mode of RelativeSource
to FindAncestor
to get ContextMenu
:
<MenuItem Header="{DynamicResource save}"
Command="{Binding Path=PlacementTarget.DataContext.CreateFiles,
RelativeSource={RelativeSource Mode=FindAncestor,
AncestorType=ContextMenu}}" />
You have set PlacementRectangle
property to refer to itself ie ContextMenu
. Don't set that property, ContextMenuService
internally set PlacementRectangle
to the element on which it is applied (in your case it will be Button).
Remove this PlacementRectangle="{Binding RelativeSource={RelativeSource Self}}"
from ContextMenu.
It should be:
<ContextMenu x:Name="MainContextMenu"
MouseLeave="ContextMenuMouseLeave" Background="White"
BorderBrush="#FF959595" SnapsToDevicePixels="False">
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.