首页 > 解决方案 > 箭头键绑定不触发

问题描述

我试图让四个箭头键绑定到我的命令ViewModel,但它们不起作用。我有一个ContentControl这样的WindowInputBindings

<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 键可以正常工作,但四个箭头键不能。为什么是这样?它们的设置完全相同。我想这可能与 s 有关,DataContext所以我将KeyBindings 放在 Window sInputBindings` 中,但这是同样的问题。

编辑:我已经测试了键盘上的每个键。除四个箭头键外,每个键都能正常触发。我检查Content了是否ContentControl吞下了这些事件,但事实并非如此。事实上,ControlContent有它自己的 keydown 事件,它也永远不会被调用,previewkeydown 也不会被箭头键调用。

标签: c#wpfxamlmvvm

解决方案


我复制了你的代码,它似乎工作正常。

我认为这在您的情况下不起作用的唯一原因(特别是如果Esc有效,但不是其他键)是您在内部使用的任何内容ContentControl也包含方向键的输入绑定。

在这种情况下,内容中的绑定将覆盖您为ContentControl自身设置的绑定。


推荐阅读