c# - wpf 菜单项的键盘快捷键

标签 c# wpf keyboard-shortcuts menuitem

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

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

使用Ctrl+O

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

有什么解决办法吗?

最佳答案

InputGestureText只是一个文本。它不会将键绑定(bind)到 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

您可以做的是在您的窗口中使用分配的输入手势创建 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 中将该命令绑定(bind)到某个方法,将该命令设置为针对 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>

关于c# - wpf 菜单项的键盘快捷键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29814612/

相关文章:

c# - 使用反斜杠作为模式终止符的正则表达式

c# - 将 Microsoft.AspNetCore.Http.HttpRequest 转换为 HttpRequestMessage

eclipse - Visual Studio 的 Eclipse 按键绑定(bind)

vim - 在 Vim 中重置缓冲区

c# - 使用 System.Xml.Serialization.XmlSerializer 反序列化有效 xml 文件时存在差异

c# - 为什么 <enum> 的集合无法转换为 <int?>?

c# - 如何在 WPF 中绑定(bind) Observable 集合的总和

c# - 在 wpf 项目中查找未卡住的画笔

c# - 任务取消暂停 UI

c# - WPF 中的高级/复杂快捷方式