Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you add access keys (shortcuts) to a WPF ContextMenu, programmatically?

I already have the following:

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);

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.

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.

like image 279
Jordan Morris Avatar asked Oct 22 '22 20:10

Jordan Morris


1 Answers

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));

The RelayCommand class used here is not the part of WPF but it's widely used in MVVM-based apps.

Please note though, that you cannot set your shortcut to X without modifiers. Quote from MSDN

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.

If for some reason you need to use X w/o modifiers - you will have to handle keyboard events (eg KeyDown) and react accordingly

like image 159
olldman Avatar answered Oct 31 '22 19:10

olldman