【问题标题】:KeyBinding without a command in WPF在 WPF 中没有命令的 KeyBinding
【发布时间】:2011-04-10 20:11:42
【问题描述】:

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

【问题讨论】:

    标签: wpf key-bindings


    【解决方案1】:

    我能想到为什么任何人想要使用命令对象的唯一原因是,他们是否将它们与视图模型相关联,而他们想要他们的键绑定只在视图中工作。

    确实,如果您尝试在视图中声明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}}" />
        (...)
    

    ReportCommandMyView 中的 ICommand,而不是 ViewModel。

    【讨论】:

      【解决方案2】:

      【讨论】:

      • 因此,更简单的方法似乎只是让步并使用命令对象。明白了。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-03
      • 1970-01-01
      • 2014-04-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多