自定义命令忽略热键

Jon*_*ood 6 c# wpf xaml

我正在编写我的第一个WPF应用程序,并试图让我的自定义命令工作.

public static RoutedUICommand Header1 { get; private set; }

.
.
.

gestures = new InputGestureCollection();
gestures.Add(new KeyGesture(Key.D1, ModifierKeys.Control, "Ctrl+1"));
Header1 = new RoutedUICommand("Header 1", "Header1", typeof(EditCommands), gestures);
Run Code Online (Sandbox Code Playgroud)

然后CommandBindings我在我的窗口的XAML中添加了一个部分.

<!-- local refers to my application's namespace -->
<Window.CommandBindings>
    <CommandBinding Command="local:EditCommands.Header1" Executed="CommandBinding_Executed" CanExecute="CommandBinding_CanExecute"></CommandBinding>
</Window.CommandBindings>
Run Code Online (Sandbox Code Playgroud)

最后,在关联的Ribbon控件中添加了一个命令条目.

<RibbonButton Label="Header 1" Command="local:EditCommands.Header1" SmallImageSource="Images\small.png" ToolTipTitle="Header 1" ToolTipDescription="" ToolTipImageSource="Images\small.png"></RibbonButton>
Run Code Online (Sandbox Code Playgroud)

单击功能区按钮可按预期执行处理程序.然而,紧迫Ctrl+1似乎根本没有效果.如何识别我的热键?

Kor*_*ill 1

找到了这个例子。也许您缺少KeyBindingInputBindings.Add零件。

KeyGesture keyg = new KeyGesture(Key.V, ModifierKeys.Control);  
KeyBinding kb = new KeyBinding(Window1.CtrlVCommand,keyg);  
InputBindings.Add(kb); 
Run Code Online (Sandbox Code Playgroud)

您的代码看起来非常相似,但缺少您所显示的内容。

我在搜索后发现了大约 5 个链接wpf ribbon button shortcut key

为了使上述示例能够像您想要的那样使用 Ctrl+1,我更新了这一行,如下所示:

KeyGesture keyg = new KeyGesture(Key.D1, ModifierKeys.Control);
Run Code Online (Sandbox Code Playgroud)

如果这不起作用,也许您可​​以采用上面的工作示例,开始将项目中的各个部分添加到其中,然后查看它何时/何​​处损坏。如果您可以发布一个完整的、最小的解决方案来展示此问题,也许我/我们可以进行调试。

更多信息:

在对此进行更多研究时,我遇到了有关输入绑定#1084 A KeyBinding Binds a Command to a Key的参考

用户界面元素有一个 CommandBindings 集合,其中包含命令绑定对象,这些对象指示该元素支持哪些命令以及该命令绑定到的代码。

用户界面元素还具有一个包含 KeyBinding 和 MouseBinding 实例的 InputBindings 集合,每个实例都将键盘或鼠标输入映射到 CommandBindings 集合中也存在的命令。

最后,还有关于InputBinding的MSDN