当事件在 View 中触发时,ReactiveUI 在 ViewModel 上调用命令

ReactiveUI Invoke Command on ViewModel when event fires in View

我正在使用 Reactive UI 事件扩展到 Reactive UI。

只是尝试获取事件以连接到 ViewModel。

最初我在视图的构造函数中有

        this.Events().KeyDown.Select(x => x.Key).InvokeCommand(ViewModel.NewTextCommand);

但是,这在构造函数中存在问题,视图模型尚不存在。我考虑过添加 WhenAnyValue 并设置 Invoke 但不确定这是否会导致内存泄漏。

目前我有

        this.Events().KeyDown.Select(x => x.Key).Subscribe(
            x =>
            {
                if (ViewModel != null)
                {
                    if (ViewModel.NewTextCommand.CanExecute(x))
                    {
                        ViewModel.NewTextCommand.Execute(x);
                    }
                }
            });

虽然这看起来有点笨拙。

你当然可以使用 WhenAnyValue,但 ReactiveUI 中还有一个内置的 InvokeCommand overload 可以做到这一点:

this.Events().KeyDown.Select(x => x.Key).InvokeCommand(this, v => v.ViewModel.NewTextCommand);