0

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

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

谢谢!

4

2 回答 2

3

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

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

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

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

于 2009-08-17T22:05:40.223 回答
1

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

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

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

于 2009-08-17T22:04:53.843 回答