I want to implement Keyboard shortcuts for a MenuItem
. I have used the code below:
One solution that doesn't involve commands and bindings is to override the owning Window's OnKeyDown
method and search a menu item that has a KeyGesture
that matches the keyboard event.
Here is the code for the Window's OnKeyDown override:
protected override void OnKeyDown(KeyEventArgs e)
{
base.OnKeyDown(e);
// here I suppose the window's menu is named "MainMenu"
MainMenu.RaiseMenuItemClickOnKeyGesture(e);
}
And here is the utility code that matches a menu item with the keyboard event:
public static void RaiseMenuItemClickOnKeyGesture(this ItemsControl control, KeyEventArgs args) => RaiseMenuItemClickOnKeyGesture(control, args, true);
public static void RaiseMenuItemClickOnKeyGesture(this ItemsControl control, KeyEventArgs args, bool throwOnError)
{
if (args == null)
throw new ArgumentNullException(nameof(args));
if (control == null)
return;
var kgc = new KeyGestureConverter();
foreach (var item in control.Items.OfType