How can I bind a command to a local event?

夙愿已清 提交于 2019-12-04 14:52:12

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;

I realize I'm really late to this particular party, but since I've been working on something similar, this is the approach I took, based on Paul's advice:

var keyDownSub= Observable.FromEventPattern<KeyEventHandler, KeyEventArgs>(
            ev => txtbxCommandLine.KeyDown += ev,
            ev => txtbxCommandLine.KeyDown -= ev
            ).Select(x => x.EventArgs)
            .Where(x => 
                x.KeyCode.ToString().ToUpper().Equals("RETURN") 
                && (_returnKeyPressed || x.Alt || x.Control))
            .InvokeCommand(_mainViewModel.ProcessCommandLine);

This seems to work perfectly fine in WinForms, if it is a bit more verbose than it would be in WPF.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!