Question

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?

Était-ce utile?

La solution

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>
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top