繁体   English   中英

wpf菜单项的键盘快捷键

[英]Keyboard shortcut for wpf menu item

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

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

使用Ctrl + O.

但它没有用 - 它没有调用Click选项。

这有什么解决方案吗?

InputGestureText只是一个文本。 它不会将键绑定到MenuItem

此属性不会将输入手势与菜单项相关联; 它只是将文本添加到菜单项。 应用程序必须处理用户的输入以执行操作

您可以做的是在窗口中使用指定的输入手势创建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)
        }));

    //...
}

然后在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>

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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