StuartMorgan
StuartMorgan

Reputation: 678

KeyBinding on KeyUp OR propagate KeyUp to Window

So I have the following KeyBindings:

<Page.InputBindings>
    <KeyBinding Key="Space" Command="{Binding AcceptCommand}" />
    <KeyBinding Key="Esc" Command="{Binding CancelCommand}"/>
</Page.InputBindings>

I also use an attached behavior to propagate the InputBindings to the ancestor Window, since if I don't there are focus issues and the commands don't always get called when I want them to. Here's a link to the handy method of doing that.

My problem is that the KeyBindings happen on KeyDown, and I want them to happen on KeyUp. From what I've read, that's just not possible and you instead have to handle the KeyUp event and do everything from code-behind. While that's not ideal I'll do it if I have to, however I don't know how I'd propagate the KeyUp from the Page to the Window.

I tried making an attached behavior similar to the one for the input bindings, but the nature of events is I can't detach events nor check whether the event is null unless I'm in the actual class that owns the event (in this case, Page).

Anyone have any ideas on how to accomplish this?

Upvotes: 1

Views: 1367

Answers (1)

Juan Pablo Garcia Coello
Juan Pablo Garcia Coello

Reputation: 3232

I made the following KeyUpBinding from InputBinding, in case you need to add more dependency properties as CommpandParameter just add as an object:

 public class KeyUpBinding : InputBinding
{
    public Key Key
    {
        get { return (Key)GetValue(KeyProperty); }
        set { SetValue(KeyProperty, value); }
    }

    public static readonly DependencyProperty KeyProperty =
        DependencyProperty.Register("Key", typeof(Key), typeof(KeyUpBinding), new PropertyMetadata(Key.A, KeyChanged));

    private static void KeyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var keybinding = (d as KeyUpBinding);

        Keyboard.AddKeyUpHandler(App.Current.MainWindow, (s, ku) =>
        {
            if(keybinding.Command!=null && ku.Key == keybinding.Key && ku.IsUp)
            {
                keybinding.Command.Execute(null);
            }
        });
    }


    public ICommand Command
    {
        get { return (ICommand)GetValue(CommandProperty); }
        set { SetValue(CommandProperty, value); }
    }

    public static readonly DependencyProperty CommandProperty =
        DependencyProperty.Register("Command", typeof(ICommand), typeof(KeyUpBinding), new PropertyMetadata(null));


}

Upvotes: 0

Related Questions