views:

44

answers:

1

I have some inputbindings 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.

A: 

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;
}
Mart
Thanks for your answer, I added some more details. I suspect I have some problems with my ICommand implementation, but I don't know what.
Tamás Szelei
I added this event handler and whats really interesting is that it does not fire for the three binded keys (space, left and R). I'm very confused.
Tamás Szelei
It worked for me in a sample project where I used a binding to the existing ApplicationCommands.open command. The three keys responded correctly. I can append my sample if you want, but there is almost nothing more in it.
Mart