1

I have this in MainWindow.xaml:

<Window.InputBindings>
  <KeyBinding Key="O" Modifiers="Control" Command="{Binding OpenCommand}" />
  <KeyBinding Key="S" Modifiers="Control" Command="{Binding SaveCommand}" />
</Window.InputBindings>

I have several child views with their own viewmodels. For instance, I have a FileView with a FileViewModel and a DataView with a DataViewModel. In both viewmodels I have an implementation of the OpenCommand:

public ICommand OpenCommand
{
    get
    {
        if (openCommand == null)
        {
            openCommand = new RelayCommand(param => this.OpenFile());
        }

        return openCommand;
    }
}

When I press Ctrl+O I want the OpenCommand command to be executed for the active view's viewmodel. Hence, if I press the keys in my FileView, OpenFile() would be executed. If I enter the keys in my DataView, OpenData() would be executed. Sort of an MDI behavior.

The code above does not work.

How do you implement this type of keybinding/command handling?

l33t
  • 18,692
  • 16
  • 103
  • 180
  • Why not add a KeyBinding for the OpenCommand in the FileView as well as in the DataView? It should solve your issue right? – Anand Murali Jan 30 '13 at 13:22

1 Answers1

1

Since you have a separate implementation for the OpenCommand in FileView and DataView, you should add a KeyBinding to these views also.

<Page.InputBindings>
    <KeyBinding Key="O" Modifiers="Control" Command="{Binding OpenCommand}" />
    <KeyBinding Key="S" Modifiers="Control" Command="{Binding SaveCommand}" />
</Page.InputBindings>

or

<UserControl.InputBindings>
    <KeyBinding Key="O" Modifiers="Control" Command="{Binding OpenCommand}" />
    <KeyBinding Key="S" Modifiers="Control" Command="{Binding SaveCommand}" />
</UserControl.InputBindings>
Anand Murali
  • 4,091
  • 1
  • 33
  • 46
  • Thanks. But what happens if you press Ctrl+O in some other window? It won't work. E.g. In a tab view, there is a `FileView` and some other views. Ctrl+O should work in the other views too. Do I need to add the command binding to ALL views? – l33t Jan 30 '13 at 13:30
  • In your case you have to add KeyBinding in MainWindow, FileView and in DataView. If Ctrl+O is pressed in some other view, the KeyBinding in MainWindow will be executed. If Ctr+O is pressed in DataView and if DataView has the focus then KeyBinding in DataView will be executed otherwise the KeyBinding in MainWindow will be executed. – Anand Murali Jan 30 '13 at 13:50
  • Yes, that's what I realized when I experimented here. Thanks. – l33t Jan 30 '13 at 15:41