Disabled MenuItems in WPF

Maybe this is a bug: Creating a ContextMenu as child of a Canvas, the event handlers CanExecute and Execute have never been executed? This took me almost two hours to figure out why. Basically, I do my command binding like

CommandBinding exitCmd = new CommandBinding(DesignerCommands.Exit);
exitCmd.CanExecute += new CanExecuteRoutedEventHandler(exitCmd_CanExecute);
exitCmd.Executed += new ExecutedRoutedEventHandler(exitCmd_Executed);
CommandBindings.Add(exitCmd);

To me, it looks like there is a minor problem in command binding whilst using command binding this manner in controls which never get the focus (such as a Canvas). Since the handlers are never fired. An easy workaround is to add additional command binding within your XAML code.

<ContextMenu.CommandBindings>
 <CommandBindingCommand="e:MyCommands.Exit" CanExecute="exitCmd_CanExecute" Executed="exitCmd_Executed"/>
</ContextMenu.CommandBindings>

I checked a couple of web sites and found one site, where the problem is described a bit more in detail. Also Aaron describes a second work around that requires some lines of code.

Leave a Reply