Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 842
jlp Avatar asked Nov 15 '10 16:11

jlp


1 Answers

<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.

like image 181
Akash Kava Avatar answered Sep 22 '22 02:09

Akash Kava