在 WPF 中创建一个简单的、未修改的键绑定

发布于 2024-12-17 18:06:49 字数 499 浏览 5 评论 0原文

我正在尝试创建一个非常简单的 WPF 应用程序。我希望在用户按“H”(不是 Control-H 或 Alt-H,只是 H)时调用命令处理程序。如果我在代码隐藏代码中使用以下内容:

var gesture = new KeyGesture(Key.H, ModifierKeys.None);
var inputBinding = new InputBinding(MyRoutedCommand, gesture);
InputBindings.Add(inputBinding);

我立即收到一个异常,指出 KeyGesture 不支持键和修饰符组合。

(如果我创建 XAML 来执行类似的操作,我会得到相同的异常)。

我的应用程序不接受键入的输入,应用程序中没有文本框,因此与文本实际上没有冲突(至少在我看来)。我没想到这会如此不寻常。

我在其他地方看到过评论,建议我可以为此创建一个自定义控件或在较低级别拦截键盘按键,但这些看起来开销很大。还有更简单的想法吗?

I'm trying to create a very simple WPF application. I'd like to have an command handler called when the user presses "H" (not Control-H or Alt-H, just H). If I use the following in code-behind code:

var gesture = new KeyGesture(Key.H, ModifierKeys.None);
var inputBinding = new InputBinding(MyRoutedCommand, gesture);
InputBindings.Add(inputBinding);

I immediately get an exception saying that the key and modifier combination isn't supported for KeyGesture.

(I get the same exception if I create the XAML to do the analogous thing).

My application doesn't accept typed input, no text boxes are in the application, so there isn't really a conflict with text (at least in my mind). I wouldn't have thought that this would be so unusual.

I've seen comments elsewhere that suggest that I could create a custom control for this or intercept keyboard presses at a low level, but these seem like a lot of overhead. Any simpler thoughts?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

扶醉桌前 2024-12-24 18:06:49

不要使用 KeyGesture 类型或属性(因为一个按键不是手势)。

例如

KeyBinding b = new KeyBinding()
    {
        Command = MyRoutedCommand,
        Key = Key.H
    };
InputBindings.Add(b);

XAML 相同

<KeyBinding Command="{Binding MyRoutedCommand}" Key="H" />

Don't use the KeyGesture type or property (as one key is not a gesture).

e.g.

KeyBinding b = new KeyBinding()
    {
        Command = MyRoutedCommand,
        Key = Key.H
    };
InputBindings.Add(b);

Same for XAML

<KeyBinding Command="{Binding MyRoutedCommand}" Key="H" />
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文