开发者

How to grab keyboard from child controls in WPF?

I have some inputbindings开发者_C百科 in a Window:

<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>

The commands are defined in my viewmodel as 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;
}

In the ViewModel's constructor:

StepNext = new RelayCommand(DoStepNext, CanStepNext);

This works fine. However, whenever I select an item in a listbox (which is a child of the Window), the KeyBindings stop working. How can I make the parent capture the keybindings regardless of which child has focus (if any). (shouldn't the events bubble up anyway?)

I'm aware that there is a PreviewKeyDown event that does just this, but that would make my ICommands useless, so I'd prefer a declarative solution if possible.

Thanks in advance.


As far as I know, there is no declarative way to make handled events continue bubbling up.

As you said, the simplest way is to handle Preview events.

As an alternative, you can override your ListBox class OnKeyDown method like this:

protected override void OnKeyDown(KeyEventArgs e)
{
    base.OnKeyDown(e);
    if (e.Key == Key.Space || e.Key == Key.Left)
        e.Handled = false;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜