在WPF中没有命令的KeyBinding

时间:2010-09-10 17:03:38

标签: wpf key-bindings

我有一个简单的WPF应用程序,我想在Win32世界中添加已知的键盘加速器。看起来KeyBinding是票证,但它需要绑定到Command对象。我没有使用命令对象,也不想使用。有没有其他方法可以在命中ctrl-x键序列时触发事件?

2 个答案:

答案 0 :(得分:0)

答案 1 :(得分:0)

我能想到为什么任何人 都想使用命令对象的唯一原因是,如果他们想将命令对象与视图模型相关联,而又想它们的键绑定仅在视图内起作用。

确实,如果您尝试在视图中声明ICommand,则很难将KeyBinding绑定到该视图。

这是我在项目中解决此问题的方法:

<Window x:Class="MyNamespace.MyView"
    (...)
    xmlns:local="clr-namespace:MyNameSpace"
    (...)
    <Grid>
        <Grid.InputBindings>
            <KeyBinding Key="R" Command="{Binding ReportCommand, 
                RelativeSource={RelativeSource AncestorType=local:MyView}}" />
    (...)

ReportCommandICommand中的MyView,而不是ViewModel中的。{p>