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

查看:337
本文介绍了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.

I understand the standard way is by creating commands and then adding your shortcut keys to them as InputGestures.

这使快捷键即使未与任何控件挂钩也可以使用.而且由于菜单项可以理解键盘手势,因此,如果您将该命令挂接到菜单项上,它们将自动在菜单项文本中显示您的快捷键.

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天全站免登陆