WPF 中的键盘快捷键 [英] Keyboard shortcuts in WPF

查看:57
本文介绍了WPF 中的键盘快捷键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道使用 _ 而不是 &,但我正在查看所有 Ctrl + 类型快捷方式.

I know about using _ instead of &, but I'm looking at all the Ctrl + type shortcuts.

Ctrl+Z 用于撤销,Ctrl+S 用于保存等

Ctrl+Z for undo, Ctrl+S for save, etc.

是否有在 WPF 应用程序中实现这些的标准"方法?或者是自己动手并将它们连接到任何命令/控制?

Is there a 'standard' way for implementing these in WPF applications? Or is it a case of roll your own and wire them up to whatever command/control?

推荐答案

一种方法是将您的快捷键添加到命令中作为 InputGestures.命令实现为 路由命令.

One way is to add your shortcut keys to the commands themselves them as InputGestures. Commands are implemented as RoutedCommands.

这使快捷键即使没有连接到任何控件也能工作.由于菜单项可以识别键盘手势,因此如果您将该命令与菜单项挂钩,它们会自动在菜单项文本中显示您的快捷键.

This enables the shortcut keys to work even if they're not hooked up to any controls. And since menu items understand keyboard gestures, they'll automatically display your shortcut key in the menu items text, if you hook that command up to your menu item.

  1. 创建静态属性以保存命令(最好作为您为命令创建的静态类中的属性 - 但举个简单的例子,只需在 window.cs 中使用静态属性):

  1. Create static attribute to hold a command (preferably as a property in a static class you create for commands - but for a simple example, just using a static attribute in window.cs):

 public static RoutedCommand MyCommand = new RoutedCommand();

  • 添加应该调用方法的快捷键:

  • Add the shortcut key(s) that should invoke method:

     MyCommand.InputGestures.Add(new KeyGesture(Key.S, ModifierKeys.Control));
    

  • 创建一个命令绑定,指向您在执行时调用的方法.将这些放在它应该在其下工作的 UI 元素(例如,窗口)和方法的命令绑定中:

  • Create a command binding that points to your method to call on execute. Put these in the command bindings for the UI element under which it should work for (e.g., the window) and the method:

     <Window.CommandBindings>
         <CommandBinding Command="{x:Static local:MyWindow.MyCommand}" Executed="MyCommandExecuted"/>
     </Window.CommandBindings>
    
     private void MyCommandExecuted(object sender, ExecutedRoutedEventArgs e) { ... }
    

  • 这篇关于WPF 中的键盘快捷键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆