views:

608

answers:

2

I'm creating a WPF app and have a system tray icon with a context menu. For the menu items I want to use WPF commands but when I assign them they are always greyed out even though the (same) commands are enabled in other places.

MenuItem menuItem = new MenuItem();
menuItem.Header = "Exit";
menuItem.Command = CustomCommands.ExitApplication;
Systray.AddMenuItem(menuItem);

It works fine when I assign click events and I have tried to create a CanExecute method for the command which always sets CanExecute to true, but that doesn't help either. Anyone got an idea why the menu items are disabled?


Update: As suggested, I added a command binding to the context menu. This had the effect that it works but only after you have clicked on the menu, i.e., at first the menu items are greyed out but once you click somewhere on the menu the options become enabled.

To solve this problem I called the following, after I added the menu items to the context menu:

CommandManager.InvalidateRequerySuggested();
+1  A: 

Of the top of my head I'd guess you have to add a CommandBinding to the Menu or systray so that your command gets handled. Although I think if that were the case it would be enabled by default.

Bryan Anderson
+2  A: 

Yea I've seen this occur. Sometimes you have to tell the WPF CommandManager system to rerun the CanExecute methods. Try calling this once the ContextMenu is loaded: CommandManager.InvalidateQuerySuggested();

siz
Thx, that did the trick. The method name is actually InvalidateRequerySuggested(), though.
Morten Christiansen