简体   繁体   English

我如何实现WPF键绑定

[英]How do I implement wpf keybinding

I want to be able to allow users to change hotkeys at runtime. 我希望能够允许用户在运行时更改热键。

Does anyone have a concrete example on how to bind a key in codebehind c# to accomplish this? 有没有人有一个具体的示例,说明如何在c#背后的代码中绑定键来完成此操作?

I assume I have to do a keybinding with a RoutedCommand. 我假设我必须使用RoutedCommand进行键绑定。 Assume that I want to push a button on the UI with the hotkey. 假设我想使用热键在UI上按下按钮。

eg... Let the user push F5 to click the btnGo on the app. 例如...让用户按F5键以在应用程序上单击btnGo。

The way that commands work is a bit different from your thinking. 命令的工作方式与您的想法有些不同。 When you press a button it doesn't fire the click for a button in your app. 当您按下按钮时,它不会触发您的应用程序中对按钮的点击。 Rather, you define a command (in this case, you could have a command called "Go") and you can assign this command to various elements in your application (menu items, buttons, etc.) All of these items fire the command and the command has an "Executed" function which performs the code. 而是,您定义一个命令(在这种情况下,您可以有一个名为“ Go”的命令),并且可以将此命令分配给应用程序中的各种元素(菜单项,按钮等)。所有这些项均会触发该命令,该命令具有执行代码的“执行”功能。

If you add CommandBindings to your main window then you can use hotkeys to fire those commands globally. 如果将CommandBindings添加到主窗口,则可以使用热键在全局范围内触发这些命令。 You can easily place command bindings in XAML by such code as: 您可以通过以下代码轻松地在XAML中放置命令绑定:

<Window.CommandBindings>
    <CommandBinding Command="local:MyCommands.Go" CanExecute="GoCanExecute" Executed="Go" />
</Window.CommandBindings>

To create your own command you can create a "RoutedUICommand" in code and set the default members (default name, default keybind, etc.). 要创建自己的命令,可以在代码中创建“ RoutedUICommand”,并设置默认成员(默认名称,默认键绑定等)。 You most likely want to make it a static property of a class. 您最有可能希望使其成为类的静态属性。

Then if you want to change or add keybinds for this command you can just access this static property and modify the InputGestures collection. 然后,如果要更改或添加此命令的键绑定,则可以访问此静态属性并修改InputGestures集合。 You can clear it, add new key bindings, and change them as necessary. 您可以清除它,添加新的键绑定,并根据需要更改它们。

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

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