[英]Can't wrap my head around implementing KeyBindings
I want to handle hotkeys in my application. 我想在应用程序中处理热键。 Writing a keybinding requires a command, which is fine, but it's not clear to me what is the minimum amount of work needed to implement that command.
编写键绑定需要一个命令,这很好,但是我不清楚实现该命令所需的最少工作量是多少。 All the examples I seem to find are over-engineered, unclear or assume I'm using the MVVM pattern which I am not.
我似乎发现的所有示例都是过度设计的,不清楚的,或者假定我使用的不是MVVM模式。
So what are the basics to getting a keybinding to work? 那么,使键绑定起作用的基本原理是什么?
Thanks! 谢谢!
The minimum amount of work needed to implement a command is simply a class that implements ICommand . 实现命令所需的最少工作量只是实现ICommand的类。 RoutedCommand is a simplistic implementation that provides the basic functionality.
RoutedCommand是提供基本功能的简化实现。
Once you have that command set up, the KeyBinding
is quite simple. 一旦设置了该命令,
KeyBinding
就非常简单。 You simply provide a Key
, and optional Modifiers
for that key. 您只需提供一个
Key
,以及该密钥的可选Modifiers
。 A number of common commands have been included in .NET. .NET中包含许多常用命令。 For example, you can bind the Copy command to Ctrl+C using this mark-up:
例如,您可以使用以下标记将“复制”命令绑定到Ctrl + C:
<Window.InputBindings>
<KeyBinding Command="ApplicationCommands.Copy" Key="C" Modifiers="Ctrl"/>
</Window.InputBindings>
You can check out ApplicationCommands , ComponentCommands , and NavigationCommands for some other built-in commands. 您可以签出ApplicationCommands , ComponentCommands和NavigationCommands以获得其他一些内置命令。
The easiest way to make a Keybinding I know of is doing something like this 进行键绑定的最简单方法是执行以下操作
in XAML 在XAML中
<Window.CommandBindings>
<CommandBinding Command="MyCommand"
CanExecute="MyCommandCanExecute"
Executed="MyCommandExecuted" />
</Window.CommandBindings>
<Window.InputBindings>
<KeyBinding Command="MyCommand" Key="M" Modifiers="Ctrl"/>
</Window.InputBindings>
in code behind 在后面的代码中
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;
}
It's pretty readable in my opinion, but if you have any questions leave a comment! 我认为这很可读,但是如果您有任何问题,请发表评论!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.