我正在使用响应式 UI 事件扩展来响应式 UI。
只是尝试获取事件以连接到 ViewModel。
最初我在 View 的构造函数中拥有
this.Events().KeyDown.Select(x => x.Key).InvokeCommand(ViewModel.NewTextCommand);
但是,这在构造函数中存在问题: View 模型尚不存在。我考虑过添加 WhenAnyValue 并设置 Invoke,但不确定这是否会导致内存泄漏。
现在我有
this.Events().KeyDown.Select(x => x.Key).Subscribe(
x =>
{
if (ViewModel != null)
{
if (ViewModel.NewTextCommand.CanExecute(x))
{
ViewModel.NewTextCommand.Execute(x);
}
}
});
不过这看起来有点笨拙。
最佳答案
你绝对可以使用WhenAnyValue
,但还有一个内置的InvokeCommand
overload在 ReactiveUI 中执行此操作:
this.Events().KeyDown.Select(x => x.Key).InvokeCommand(this, v => v.ViewModel.NewTextCommand);
关于c# - 当 View 中事件触发时,ReactiveUI 在 ViewModel 上调用命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32686943/