Finally got it working, was doing some silly mistakes!
Had to change the static
command initialization to have ContextMenu
as its owner
public static RoutedCommand MyCommand = new RoutedCommand("MyCommand", typeof(ContextMenu));
in MainWindow.xaml.cs
, added a method to register command binding and called it from MainWindow
's contructor:
private void InitializeMenuItemsCommands()
{
CommandManager.RegisterClassCommandBinding(typeof(ContextMenu), new CommandBinding(DesignerCanvas.TestDialog, OpenTestDialog, CanOpenTestDialog));
}
And finally the handlers for CanExecute
and Executed
events:
private void CanOpenTestDialog(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = true; // set if MenuItem is enabled
}
private void OpenTestDialog(object sender, ExecutedRoutedEventArgs e)
{
// handle the MenuItem click here
}
DIDN'T have to change anything in my ResourceDictionary
for MenuItem
, so here is the MenuItem again :
<MenuItem x:Name="menuItem1" Header="MySubMenuItem 1"
Command="{x:Static DesignerItems:DesignerCanvas.MyCommand}"> <<<=== Command Binding
<MenuItem.Icon>
<Image Source="myImage.png" Width="20"/>
</MenuItem.Icon>
</MenuItem>