简体   繁体   English

WPF快捷键绑定

[英]WPF shortcut key binding

I want to bind a shortcut key to my usercontrol using UserControl.InputBindings. 我想使用UserControl.InputBindings将快捷键绑定到我的用户控件。

I am not using MVVM or any other pattern. 我没有使用MVVM或任何其他模式。 I just want to bind this key using the code behind file of a XAML file. 我只想使用XAML文件的文件后面的代码绑定此密钥。

You can do key binding like this in XAML: 您可以在XAML中像这样进行键绑定:

<UserControl.InputBindings>
    <KeyBinding Command="{Binding SomeCommand}" Key="F5"/>
</UserControl.InputBindings>

If you want to assign a keybinding, and you want to do it from the code-behind, this would be the easiest way: 如果您想分配一个键绑定,并且想从后面的代码中进行,这是最简单的方法:

using System.Windows.Input;

var cmd = new RoutedCommand();
userControl.InputBindings.Add(new KeyBinding(cmd, your_key_gesture_here));
userControl.CommandBindings.Add(new CommandBinding(cmd, your_event_handler_here));

Replace your_key_gesture_here with the shortcut key you want to trigger, and replace your_event_handler_here with the method you want to be triggered when the key is pressed. your_key_gesture_here替换为要触发的快捷键,并将your_event_handler_here替换为要在按下该键时触发的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM