简体   繁体   中英

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?

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>

你应该以这种方式成功:通过使用KeyBindings 定义MenuItem快捷方式

<Window.CommandBindings> <CommandBinding Command="New" Executed="CommandBinding_Executed" /> </Window.CommandBindings> <Window.InputBindings> <KeyBinding Key="N" Modifiers="Control" Command="New"/> </Window.InputBindings>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM