WPF MVVM中的键盘快捷键? [英] Keyboard shortcuts in WPF MVVM?

查看:568
本文介绍了WPF MVVM中的键盘快捷键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有遵循MVVM模式的WPF应用程序.我需要实现键盘快捷键.这些快捷方式必须控制WebBrowser控件的行为.我定义了第一个自定义命令,并将其添加到视图的输入绑定中.将会有更多的命令,它们将不得不在浏览器上调用脚本:

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;
    }

我的问题是如何使它适合MVVM模式? MVVM对我来说是一个新概念,但我了解如何将view的命令绑定到视图模型并执行方法或更改属性. 但是,在这种情况下,我需要在视图中的控件上执行一种方法.在这种情况下,快捷方式处理的最佳位置是什么?

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>

您可以将命令属性绑定到View Model的命令.

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

这篇关于WPF MVVM中的键盘快捷键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆