views:

949

answers:

2

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.

+3  A: 

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.

Trent F Guidry
Trent F Guidry
this is so weird but it works, thank you :)
arconaut
A: 

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 http://stackoverflow.com/questions/616206/wpf-usercontrol-and-commands-oh-my

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}}}"/>
ExistMe