Keyboard shortcuts in WPF MVVM?

我怕爱的太早我们不能终老 提交于 2019-11-30 12:57:04

问题


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?


回答1:


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



来源:https://stackoverflow.com/questions/4186378/keyboard-shortcuts-in-wpf-mvvm

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!