I am developing an MVVM application. I have a main Window, which looks more or less like this:
<Window>
<ContentControl Content={Binding ContentViewModel} />
</Window>
Then I have this ViewModel, which exposes a certain number of Commands, and I want these commands to be available to the user both from the UI (with buttons, etc), AND from the keyboard, using KeyBindings.
The commands work properly from the UI buttons. But the Keybindings don’t always work, it’d seem to me that the problem is that the loaded view is not always in focus.
This is the code for the view.
<UserControl>
<UserControl.InputBindings>
<KeyBinding Key="Delete" Command="{Binding RemoveEntityCommand, ElementName=Designer}" />
</UserControl.InputBindings>
<Grid>
<namespace:Designer x:Name="Designer" />
</Grid>
</UserControl>
How to solve this permanently for an MVVM application? I’ve encountered this problem multiple times.
Note: all namespace declarations removed for simplicity.
Thanks.
I would probably attach a Command to the KeyDown or KeyUp event of the
Windowinstead of theUserControl, and route it from there.It can either be routed to the
ShellViewModel, which will in turn pass it to the currentContentViewModelif needed, or perhaps use some kind of Messaging system that broadcasts special key combinations, and ViewModel’s can subscribe to them.