简体   繁体   中英

Keyboard shortcuts in WPF MVVM?

I have WPF application that follow MVVM pattern. I need to implement keyboard shortcuts. These shortcut have to contol WebBrowser control behaviour. I defined first custom command and added to view's inputbindings. There will be much more commands and they would have to invoke scripts on browser:

MainWindow.xaml.cs:

        ...

        CommandBinding cb = new CommandBinding(RemoteControlCommands.TestCommand, MyCommandExecuted,  MyCommandCanExecute);
        this.CommandBindings.Add(cb);

        KeyGesture kg = new KeyGesture(Key.Q, ModifierKeys.Control);
        InputBinding ib = new InputBinding(RemoteControlCommands.TestCommand, kg);
        this.InputBindings.Add(ib);
    }

    private void MyCommandExecuted(object sender, ExecutedRoutedEventArgs e)
    {
        webBrowser.InvokeScript("foo", "Hello World!");
    }

    private void MyCommandCanExecute(object sender, CanExecuteRoutedEventArgs e)
    {
        e.CanExecute = true;
    }

My question is how to fit this into MVVM patern? MVVM is a new concept to me but I understand how to bind view's command to view model and there execute methods or change properties. However what I need in this case is to execute a method on a control in the view. What is the best place to shortcut handling in this scenario?

<Window.InputBindings>
  <KeyBinding Command="{Binding MyCommand, Source=viewModel...}"
              CommandParameter="{Binding,ElementName=browserControl,Mode=Self}"
              Gesture="CTRL+R" />
</Window.InputBindings>

You can bind command property to View Model's command.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM