Reputation: 3285
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.
Upvotes: 4
Views: 2365
Reputation: 529
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}}}"/>
Upvotes: 1
Reputation: 96
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.
Upvotes: 4