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.CommandBi开发者_如何学JAVAndings.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.
精彩评论