我正在尝试使用以下方法向我的 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
。在这种情况下,InputGestureText
和 Header
都将从 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/