箭头键绑定不触发 [英] Arrow key bindings not firing
问题描述
我正在尝试将四个箭头键绑定到我的 ViewModel
中的命令,但它们不起作用.我在带有 InputBindings
的 Window
中有一个 ContentControl
像这样:
I'm trying to get the four arrow keys to be bound to a command in my ViewModel
, but they are not working. I have a ContentControl
in a Window
with InputBindings
like so:
<ContentControl.InputBindings>
<KeyBinding Command="{Binding EndCmd}" Key="Esc" />
<KeyBinding Command="{Binding PanUpCmd}" Key="Up" />
<KeyBinding Command="{Binding PanDownCmd}" Key="Down" />
<KeyBinding Command="{Binding PanLeftCmd}" Key="Left" />
<KeyBinding Command="{Binding PanRightCmd}" Key="Right" />
</ContentControl.InputBindings>
在我的 ViewModel
中:
public RelayCommand EndCmd { get; set; }
public RelayCommand PanUpCmd { get; set; }
public RelayCommand PanDownCmd { get; set; }
public RelayCommand PanLeftCmd { get; set; }
public RelayCommand PanRightCmd { get; set; }
public MainViewModel()
{
EndCmd = new RelayCommand(End);
PanUpCmd = new RelayCommand(PanUp);
PanDownCmd = new RelayCommand(PanDown);
PanLeftCmd = new RelayCommand(PanLeft);
PanRightCmd = new RelayCommand(PanRight);
}
//functions that the commands call here
现在,Escape 键工作正常,但四个箭头键不工作.为什么是这样?它们的设置完全相同.我想也许这与 DataContext
有关,所以我将 KeyBinding
s 放在 Windows
InputBindings` 中,但这是同样的问题.
Now, the Escape key works fine, but the four arrow keys do not. Why is this? They are set up exactly the same. I thought maybe it was something to do with the DataContext
so I put the KeyBinding
s in the Windows
InputBindings` but it was the same issue.
我已经测试了键盘上的每个键.除了四个箭头键外,每个键都能正确触发.我检查了 ContentControl
的 Content
是否正在吞噬事件,但事实并非如此.事实上,作为 Content
的 Control
有它自己的 keydown 事件,它也永远不会被调用,也不会调用 previewkeydown 和箭头键.
I've tested every key on my keyboard. Every key fires properly except the four arrow keys. I checked if the Content
of the ContentControl
was swallowing the events, and it was not. In fact, the Control
that is the Content
has it's own keydown event, which is also never called, nor is the previewkeydown, with the arrow keys.
推荐答案
我复制了您的代码,它似乎工作正常.
I copied your code and it seems to work fine.
我认为这在您的情况下不起作用的唯一原因(特别是如果 Esc
有效,但其他键无效)是您在 中使用的任何内容ContentControl
还包含方向键的输入绑定.
The only reason I can think for this not to work in your case (especially if Esc
works, but not the other keys) is that whatever content you're using inside of the ContentControl
also contains input bindings for the direction keys.
在这种情况下,内容中的绑定将覆盖您为 ContentControl
本身设置的绑定.
In this case, the bindings in the content would override the bindings you've set for the ContentControl
itself.
这篇关于箭头键绑定不触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!