如何以编程方式将访问键(快捷方式)添加到WPF ContextMenu? [英] How do you add access keys (shortcuts) to a WPF ContextMenu, programmatically?
问题描述
我已经有以下内容:
var myContextMenu = new System.Windows.Controls.ContextMenu();
var exitItem = new MenuItem();
exitItem.Header = "E_xit";
exitItem.Item.Click += new RoutedEventHandler(new System.EventHandler(ExitProgram));
myContextMenu.Items.Add(exitItem);
这会使我的上下文菜单显示带下划线"x"的退出"菜单项.但是,按x不会执行任何操作.单击菜单项可以正常工作.
This causes my context menu to display the Exit menu item, with an underlined "x". However, pressing x does nothing. Clicking the menu item works fine.
如何将事件与x键相关联?请注意,这必须在我的上下文中以编程方式完成.我不能在前面的XAML中编写此解决方案.
How can I associate an event with the x key? Please note that this has to be done programmatically in my context. I cannot compose this solution in the XAML in front.
推荐答案
添加快捷方式的常用方法如下:
The usual way to add shortcuts is as follows:
var exitCommand = new RelayCommand(_ => ExitProgram());
var exitItem = new MenuItem();
exitItem.Header = "E_xit";
exitItem.Command = exitCommand;
myContextMenu.Items.Add(exitItem);
InputBindings.Add(new KeyBinding(exitCommand, new KeyGesture(Key.X, ModifierKeys.Alt));
RelayCommand 此处使用的类不是WPF的一部分,但已在基于MVVM的应用程序中广泛使用.
The RelayCommand class used here is not the part of WPF but it's widely used in MVVM-based apps.
但是请注意,没有修饰符就无法将快捷方式设置为X. 引用 MSDN
Please note though, that you cannot set your shortcut to X without modifiers. Quote from MSDN
在大多数情况下,KeyGesture必须与一个或多个关联 修改键.该规则的例外是功能键和 数字小键盘按键,可以是有效的KeyGesture 他们自己.例如,您可以仅使用 F12键,但要在KeyGesture中使用X键,必须将其与 修改键.
In most cases, a KeyGesture must be associated with one or more ModifierKeys. The exceptions to this rule are the function keys and the numeric keypad keys, which can be a valid KeyGesture by themselves. For example, you can create a KeyGesture by using only the F12 key, but to use the X key in a KeyGesture it must be paired with a modifier key.
如果由于某些原因需要使用X w/o修饰符-您将不得不处理键盘事件(例如KeyDown)并做出相应的反应
If for some reason you need to use X w/o modifiers - you will have to handle keyboard events (eg KeyDown) and react accordingly
这篇关于如何以编程方式将访问键(快捷方式)添加到WPF ContextMenu?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!