将 WPF 快捷键绑定到 ViewModel 中的命令 [英] Binding a WPF ShortCut Key to a Command in the ViewModel

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

问题描述

我有一个使用 MVVM 模式的 WPF 应用程序.将按钮连接到 VM 非常简单,因为它们实现了 ICommand.我有一个类似的上下文菜单.下一步是为上下文菜单创建快捷键.我不知道如何让快捷键调用命令.下面是一个例子:

I have a WPF app that is using the MVVM pattern. Hooking up buttons to the VM is pretty straight forward since they implement the ICommand. I have a context menu that works similar. The next step is to create shortcut keys for the context menu. I can't figure out how to get the shortcut key invoke the Command. Here is an example:

<MenuItem Header="Update" Command="{Binding btnUpdate}" >
    <MenuItem.Icon>
        <Image Source="/Images/Update.png"
               Width="16"
               Height="16" />
        </MenuItem.Icon>
    </MenuItem>

现在我添加了这个:

<Window.InputBindings>
    <KeyBinding Key="U"
                Modifiers="Control" 
                Command="{Binding btnUpdate}" />
</Window.InputBindings>

尝试将快捷键连接到相同的绑定,但这不起作用.错误是:

to try and connect the shortcut keys to the same binding, but this doesn't work. The error is:

错误 169 无法在类型为KeyBinding"的Command"属性上设置Binding".只能在 DependencyObject 的 DependencyProperty 上设置绑定".

Error 169 A 'Binding' cannot be set on the 'Command' property of type 'KeyBinding'. A 'Binding' can only be set on a DependencyProperty of a DependencyObject.

没有办法将这个事件与命令挂钩吗?我想不通.

Isn't there a way to hook up this event to the Command? I can't figure this out.

提前致谢!

账单

推荐答案

我写了一个 自定义标记扩展InputBindings绑定"到命令,几乎可以像真正的绑定一样使用:

I wrote a custom markup extension to "bind" InputBindings to commands, which can be used almost like a real binding :

<UserControl.InputBindings>
    <KeyBinding Modifiers="Control" 
                Key="E" 
                Command="{input:CommandBinding EditCommand}"/>
</UserControl.InputBindings>

请注意,此标记扩展使用私有反射,因此只有在您的应用程序完全信任运行时才能使用它...

Note that this markup extension uses private reflection, so it can only be used if your application runs in full trust...

另一种选择是使用 CommandReference 类.它可以在 此处 的 MVVM 工具包中找到.这可能是一种更简洁的方法,但使用起来有点复杂.

Another option is to use the CommandReference class. It can be found in the MVVM toolkit available here. It's probably a cleaner approach, but a bit more complex to use.

请注意,在 WPF 4 中,InputBinding.CommandInputBinding.CommandParameterInputBinding.CommandTarget 属性是依赖属性,因此它们可以正常绑定

Note that in WPF 4, the InputBinding.Command, InputBinding.CommandParameter and InputBinding.CommandTarget properties are dependency properties, so they can be bound normally

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

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