Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I bind a command to a local event?

I have a form that should capture KeyDown/KeyUp events.

This code fails with NRE, because it looks for KeyDown control on my current view:

this.BindCommand(ViewModel, vm => vm.KeyDown, "KeyDown");

What I've done is created wrapper class that has form as a property, so I can use this overload:

this.BindCommand(ViewModel, vm => vm.KeyDown, v => v.Form, "KeyDown");

While it works, it seems like a hack to me. Is there a proper way to bind to local events?

like image 799
ionoy Avatar asked Jan 10 '23 23:01

ionoy


1 Answers

That's the right way to do it if you're using BindCommand. If you want to get rid of the string and you're using ReactiveUI.Events, you could also do:

this.Form.Events().KeyDown
    .InvokeCommand(this, x => x.ViewModel.KeyDown);

As an aside, "KeyDown" isn't a very MVVM'y command. I'd write your key => command mappings at the View layer, like this (coding via TextArea, ignore syntax bugs):

this.Form.Events().KeyDown
    .Where(x => x.Key == Key.C && (x.Modifier & Modifier.Ctrl))
    .InvokeCommand(this, x => x.ViewModel.CopyText;
like image 78
Ana Betts Avatar answered Jan 13 '23 13:01

Ana Betts