4

A quite simple and straightforward example.

I have a window. It has CommandBindings set to catch a RoutedUICommand execution.

<Window
   ...
   >
   <Window.CommandBinding>
       <CommandBinding 
           Command="{x:Static local:Commands.Command1}"  
           Executed="OnCommand1Executed" 
           CanExecute="OnCanCommand1Execute" 
           />
   </Window.CommandBinding>
</Window>

There's a UserControl hosted in the window, inside of which a ContextMenu is declared. A ContextMenu item has the Command property assigned to the same RoutedUICommand.

<ContextMenu>
    <MenuItem Command="{x:Static local:Commands.Command1}" />
</ContextMenu>

But the menu item remains inactive (== disabled). Somehow command execution doesn't go up to the window. Maybe it's because ContextMenu is inside of a popup?

Everything works properly if I add needed CommandBinding into the ContextMenu.CommandBindings collection. But that's a terrible option to not have a place for a single 'global' CommandBinding.

How can I solve the problem in the best way?

UPD: Turns out it's not that bad. The Commands aren't bound only at the first time user opens the menu. If it's closed and reopened everything's fine. Still, it seems to be not desirable and a quite weird behavior.

arconaut
  • 3,227
  • 2
  • 27
  • 36

2 Answers2

4

Does this still occur if you add Focus(); right after InitializeComponent(); in the windows constructor?

This sounds like WPF is having an issue finding the visual tree from the context menu. Setting the focus to the main window might fix it.

  • To give credit where credit is due, I think this was the place where I first saw that workaround http://cebla5.spaces.live.com/blog/cns!1B8262ED00250003!206.entry?wa=wsignin1.0&sa=834175698 – Trent F Guidry Jun 07 '09 at 23:12
  • See http://stackoverflow.com/a/6070771 for an alternative work-around. IMHO it's a better approach -- XAML only and doesn't depend on the side-effect of focus -- but it does have the drawback of causing a spurious "Object reference not set to an instance of an object" error message in the XAML editor (just in the editor...the code still compiles and runs fine). If I could figure out a way to fix that error, I'd say the alternative was 100% preferable. – Peter Duniho Mar 14 '16 at 03:08
1

How we can handle this issue in a user control? It seems that focus doesn't work in that context

Update : I found the solution here How to set CommandTarget for MenuItem inside a ContextMenu?

Seems that it's related to CommandTarget

<MenuItem x:Name="mnuProperties" Header="_Properties"
          Command="{x:Static localcommands:TaskCommands.ViewTaskProperties}"
          CommandTarget="{Binding PlacementTarget,
          RelativeSource={RelativeSource FindAncestor,AncestorType={x:Type ContextMenu}}}"/>
Community
  • 1
  • 1
ExistMe
  • 509
  • 6
  • 18