Search code examples
c#wpfkeyboard-shortcutsmenuitem

Keyboard shortcut for wpf menu item


I am trying to add a keyboard shortcut to the menu item in my xaml code using

<MenuItem x:Name="Options" Header="_Options" InputGestureText="Ctrl+O" Click="Options_Click"/>

with Ctrl+O

But it is not working - it is not calling the Click option.

Are there any solutions for this?


Solution

  • InputGestureText is just a text. It does not bind key to MenuItem.

    This property does not associate the input gesture with the menu item; it simply adds text to the menu item. The application must handle the user's input to carry out the action

    What you can do is create RoutedUICommand in your window with assigned input gesture

    public partial class MainWindow : Window
    {
        public static readonly RoutedCommand OptionsCommand = new RoutedUICommand("Options", "OptionsCommand", typeof(MainWindow), new InputGestureCollection(new InputGesture[]
            {
                new KeyGesture(Key.O, ModifierKeys.Control)
            }));
    
        //...
    }
    

    and then in XAML bind that command to some method set that command against MenuItem. In this case both InputGestureText and Header will be pulled from RoutedUICommand so you don't need to set that against MenuItem

    <Window.CommandBindings>
        <CommandBinding Command="{x:Static local:MainWindow.OptionsCommand}" Executed="Options_Click"/>
    </Window.CommandBindings>
    <Menu>
        <!-- -->
        <MenuItem Command="{x:Static local:MainWindow.OptionsCommand}"/>
    </Menu>