c# - 自定义命令忽略热键

标签 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);

然后我将 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>

最后,向关联的功能区控件添加命令条目。

<RibbonButton Label="Header 1" Command="local:EditCommands.Header1" SmallImageSource="Images\small.png" ToolTipTitle="Header 1" ToolTipDescription="" ToolTipImageSource="Images\small.png"></RibbonButton>

单击功能区按钮会按预期执行处理程序。但是,按 Ctrl+1 似乎完全没有效果。如何识别我的热键?

最佳答案

一定有其他事情发生了。在键输入到达具有包含您的命令的命令绑定(bind)的元素之前,是否有一些元素可以处理键输入?

Snooop 是解决此类问题的有用工具。

使用下面的代码,只要按下 Ctrl+1,就会调用 HandleHeader1。

public static class MyCommands
{
    public static RoutedUICommand Header1 { get; } = new RoutedUICommand("Header 1", "Header1", typeof(MyCommands), new InputGestureCollection { new KeyGesture(Key.D1, ModifierKeys.Control, "Ctrl+1") });
}

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

    private void HandleHeader1(object sender, ExecutedRoutedEventArgs e)
    {
    }
}

<Window x:Class="WpfApplication2.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:WpfApplication2"
    mc:Ignorable="d"
    Title="MainWindow" Height="350" Width="525">
    <Window.CommandBindings>
        <CommandBinding Command="local:MyCommands.Header1" Executed="HandleHeader1"/>
    </Window.CommandBindings>
    <StackPanel>
        <TextBox/>
    </StackPanel>
</Window>

关于c# - 自定义命令忽略热键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34488490/

相关文章:

c# - 在 C# 中使用 SSE 是可能的吗?

c# - 从模型 MVC 中取消绑定(bind)属性

c# - 如何在 C# 代码后面显示 PictureBox

c# - xbox 360 kinect光束角度与属性更改有关

c# - 如何在 XAML 中将静态值传递给 IValueConverter

c# - 如何在绑定(bind)到 Canvas 的集合中找到具有特定值的项目

c# - WPF 自定义形状

xaml - 如何制作可执行的 Metro 风格应用程序?

xaml - UWP 社区工具包 AdaptiveGridView 控件仅包含一项

c# - WPF 将枚举绑定(bind)到组合框