0

I have a ContextMenu whose items are all bound to commands and enable/disable correctly after ANY Command is invoked from another source but prior to, they are all disabled. So if I run the app, all the MenuItems are disabled but if I invoke any of the bound commands from another source (buttons, for instance) they become synchronized with the CanExecute code. I have no idea how to debug this. Any thought would be helpful!?!

THelper
  • 15,333
  • 6
  • 64
  • 104
Brad
  • 1,187
  • 3
  • 23
  • 44
  • Possible duplicate of [commandbinding not working?](http://stackoverflow.com/questions/6070478/commandbinding-not-working) – Peter Duniho Mar 14 '16 at 03:03

2 Answers2

4

Seems to be a bug where there is no focused element in the window's main focus scope. A workaround is to bind MenuItem's CommandTarget to the main window.

Answer from Marco Zhou here: http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/7bd75a7c-eab4-4f3a-967b-94a9534a7455

<Window.ContextMenu>
    <ContextMenu >
      <ContextMenu.Items>
        <MenuItem Command="ApplicationCommands.Open" 
                  CommandTarget="{Binding Path=PlacementTarget,RelativeSource={RelativeSource AncestorType={x:Type ContextMenu}}}"/> 
      </ContextMenu.Items>
    </ContextMenu>
  </Window.ContextMenu>
midspace
  • 922
  • 9
  • 18
  • This works great. But the XAML editor displays a spurious "Object reference not set to an instance of an object". It works fine once compiled and run, but it'd be nice to not have the error displayed in the editor. Any way to fix that? – Peter Duniho Mar 14 '16 at 03:02
0

Sometimes you need to force WPF to re-evaluate whether commands are enabled or not.

Somewhere in your code, add a call to:

CommandManager.InvalidateRequerySuggested();

See if that helps.

Adel Hazzah
  • 8,737
  • 2
  • 20
  • 16
  • Thanks Adel, appreciate you taking the time. I've tried various locations with no joy. – Brad Mar 13 '10 at 20:41