wpf 菜单项的键盘快捷键

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29814612/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 13:06:05  来源:igfitidea点击:

Keyboard shortcut for wpf menu item

c#wpfkeyboard-shortcutsmenuitem

提问by keerthee

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

我正在尝试使用以下命令向我的 xaml 代码中的菜单项添加键盘快捷键

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

with Ctrl+O

Ctrl+O

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

但它不起作用 - 它没有调用 Click 选项。

Are there any solutions for this?

有什么解决方案吗?

回答by dkozl

InputGestureTextis just a text. It does not bind key to MenuItem.

InputGestureText只是一个文本。它不会将 key 绑定到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 RoutedUICommandin your window with assigned input gesture

您可以做的是RoutedUICommand使用指定的输入手势在您的窗口中创建

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 InputGestureTextand Headerwill be pulled from RoutedUICommandso you don't need to set that against MenuItem

然后在 XAML 中将该命令绑定到某个方法,将该命令设置为针对MenuItem. 在这种情况下,InputGestureTextHeader都将从中拉出,RoutedUICommand因此您无需将其设置为MenuItem

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

回答by tuxy42

you should succeed in this way: Defining MenuItem ShortcutsBy using KeyBindings:

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

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