如何将命令绑定到本地事件? [英] How can I bind a command to a local event?
问题描述
我有一个可以捕获 KeyDown/KeyUp 事件的表单.
I have a form that should capture KeyDown/KeyUp events.
此代码因 NRE 而失败,因为它在我当前的视图中查找 KeyDown 控件:
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?
推荐答案
如果您使用 BindCommand,这是正确的方法.如果你想摆脱字符串并且你正在使用 ReactiveUI.Events,你也可以这样做:
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);
顺便说一句,KeyDown"不是一个非常 MVVM 的命令.我会在 View 层写你的 key => 命令映射,像这样(通过 TextArea 编码,忽略语法错误):
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;
这篇关于如何将命令绑定到本地事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!