【问题标题】:Can't wrap my head around implementing KeyBindings无法实现 KeyBindings
【发布时间】:2009-08-17 21:50:21
【问题描述】:

我想在我的应用程序中处理热键。编写键绑定需要一个命令,这很好,但我不清楚实现该命令所需的最少工作量是多少。我似乎找到的所有示例都是过度设计的、不清楚的,或者假设我使用的是我没有使用的 MVVM 模式。

那么让键绑定工作的基础是什么?

谢谢!

【问题讨论】:

    标签: c# wpf key-bindings


    【解决方案1】:

    实现命令所需的最少工作量只是实现ICommand 的类。 RoutedCommand 是一个提供基本功能的简单实现。

    一旦您设置了该命令,KeyBinding 就非常简单。您只需为该密钥提供Key 和可选的Modifiers。 .NET 中包含了许多常用命令。例如,您可以使用以下标记将 Copy 命令绑定到 Ctrl+C:

    <Window.InputBindings>
        <KeyBinding Command="ApplicationCommands.Copy" Key="C" Modifiers="Ctrl"/>
    </Window.InputBindings>
    

    您可以查看ApplicationCommandsComponentCommandsNavigationCommands 了解其他一些内置命令。

    【讨论】:

      【解决方案2】:

      我知道的最简单的键绑定方法是做这样的事情

      在 XAML 中

        <Window.CommandBindings>
          <CommandBinding Command="MyCommand" 
             CanExecute="MyCommandCanExecute"
             Executed="MyCommandExecuted" />
        </Window.CommandBindings>
        <Window.InputBindings>
          <KeyBinding Command="MyCommand" Key="M" Modifiers="Ctrl"/>
        </Window.InputBindings>
      

      在代码后面

      private void MyCommandCanExecute(object sender, CanExecuteRoutedEventArgs e)
      {
        e.CanExecute = true;
        e.Handled = true;
      }
      
      private void MyCommandExecuted(object sender, ExecutedRoutedEventArgs e)
      {
        MessageBox.Show("Executed!");
        e.Handled = true;
      }
      

      我认为它的可读性很好,但是如果您有任何问题,请发表评论!

      【讨论】:

      • 嗨,戳!命令绑定真的有必要吗?如果我不需要 canexecute 怎么办?路由命令呢?我不需要以某种方式声明一个?
      • 您缺少的一条信息是键绑定导致命令被“提升”,但不是在它被提升时要做什么。然后,该命令将沿着 UI 树向上传播,直到遇到一个 CommandBinding,该命令说明当命令消息被截获时要做什么。就是这样:)
      猜你喜欢
      • 2013-09-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-07
      • 2021-12-11
      • 2017-02-14
      • 2016-11-16
      • 2015-01-25
      相关资源
      最近更新 更多