【发布时间】:2011-04-19 02:32:08
【问题描述】:
我在一个窗口中有一些输入绑定:
<Window.InputBindings>
<KeyBinding Key="Space" Command="{Binding Path=StepNext}" />
<KeyBinding Key="R" Command="{Binding Path=ResetSong}" />
<KeyBinding Key="Left" Command="{Binding Path=StepPrevious}" />
</Window.InputBindings>
这些命令在我的视图模型中定义为 RelayCommands:
public class RelayCommand : ICommand
{
private Action<object> _exec;
private Func<object, bool> _canExec;
public RelayCommand(Action<object> exec, Func<object, bool> canExec)
{
_exec = exec;
_canExec = canExec;
}
public void Execute(object parameter)
{
_exec(parameter);
}
public bool CanExecute(object parameter)
{
return _canExec(parameter);
}
public event EventHandler CanExecuteChanged;
}
在 ViewModel 的构造函数中:
StepNext = new RelayCommand(DoStepNext, CanStepNext);
这很好用。但是,每当我在列表框中选择一个项目(它是 Window 的子项)时,KeyBindings 就会停止工作。无论哪个孩子有焦点(如果有),我如何让父母捕获键绑定。 (事件不应该冒泡吗?)
我知道有一个 PreviewKeyDown 事件可以做到这一点,但这会使我的ICommands 无用,所以如果可能的话,我更喜欢声明性解决方案。
提前致谢。
【问题讨论】: