How to grab keyboard from child controls in WPF?

I have some input names in the 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>

Commands are defined in my view model 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 constructor of ViewModel:

StepNext = new RelayCommand(DoStepNext, CanStepNext);

It works great. However, when I select an item in the list (which is a child of the window), KeyBindings stop working. How can I get a parent to capture key bindings, regardless of which one has focus (if any). (Shouldn't they still bubble?)

I know that there is a PreviewKeyDown event that does just that, but it will make mine ICommanduseless, so I would prefer, if possible, a declarative solution.

Thanks in advance.

+3
1

, , .

, Preview.

OnKeyDown ListBox :

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

Source: https://habr.com/ru/post/1767274/


All Articles