Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 747
keerthee Avatar asked Nov 29 '25 12:11

keerthee


1 Answers

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>
like image 131
dkozl Avatar answered Dec 02 '25 02:12

dkozl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!