1
votes

I have a MainView (Window) as a shell in which i load different UserControls containing different "pages" or "views" when the user navigates the application.

I change view by setting a ViewModel to a Content property on the MainView. A DataTemplate selects the right View depending on the ViewModel.

I want to use a F1 keyboard shortcut to trigger a command on the current UserControl.

If I add InputBindings on the UserControl I have to select something in the UserControl before I can hit F1.

If I add InputBindings on the Window I don't have the right DataContext (ViewModel). I have even tried setting CommandTarget to the Content property of the ViewModel

<Window.InputBindings>
    <KeyBinding Key="F1" CommandTarget="{Binding ElementName=ContentControl}" Command="{Binding ShowInfoCommand}" />
</Window.InputBindings>

I have also tried setting FocusManager.FocusedElement="{Binding ElementName=ContentControl}" on MainWindow and Focusable=true on the UserControl and even the ContentControl.

1

1 Answers

1
votes

I found a good solution here at SO by Adi Lester. He is using a behavior to propagate the keybindings from the UserControl to the Window

I've found that if you are using the behavior in a generic contenttemplate in generic.xaml you have to bind the command via TemplatedParent and not TemplateBinding

<Border behaviors:InputBindingBehavior.PropagateInputBindingsToWindow="True">
    <Border.InputBindings>
        <KeyBinding Key="F1" Command="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=ShowInfoCommand}" />
    </Border.InputBindings> 
</Border>