c# – 如何直接调用ReactiveUI 7中的ReactiveCommand.Execute()
发布时间:2020-12-15 04:26:38 所属栏目:百科 来源:网络整理
导读:我正在尝试将我的项目从ReactiveUI 6.5转换为版本7.在旧版本中我调用了 // var command = ReactiveCommand.Create...;// ...if(command.CanExecute(null)) command.Execute(null); 为了从我的代码后面执行命令. 现在,CanExecute方法不再可用,并替换为IObserv
我正在尝试将我的项目从ReactiveUI 6.5转换为版本7.在旧版本中我调用了
// var command = ReactiveCommand.Create...; // ... if(command.CanExecute(null)) command.Execute(null); 为了从我的代码后面执行命令. 现在,CanExecute方法不再可用,并替换为IObservable< bool>的属性.如果我只是调用Execute(),是否会自动调用CanExecute Observable.Subify()或者我必须显式调用它吗? 现在我用上面的代码替换了 command.Execute().Subscribe(); 解决方法
我找到了三种不同的解决方案来调用我的命令的CanExecute和Execute方法,就像我之前在ReactiveUI 6.5中那样:
选项1 这等于6.5版本中的调用,但我们需要将命令显式转换为ICommand: if (((ICommand) command).CanExecute(null)) command.Execute().Subscribe(); 选项2 if(command.CanExecute.FirstAsync().Wait()) command.Execute().Subscribe() 或异步变体: if(await command.CanExecute.FirstAsync()) await command.Execute() 选项3 另一个选择是使我们使用InvokeCommand扩展方法. Observable.Start(() => {}).InvokeCommand(ViewModel,vm => vm.MyCommand); 这尊重命令的可执行性,如documentation中所述. 为了让它更舒服,我编写了一个小扩展方法来提供ExecuteIfPossible和GetCanExecute方法: public static class ReactiveUiExtensions { public static IObservable<bool> ExecuteIfPossible<TParam,TResult>(this ReactiveCommand<TParam,TResult> cmd) => cmd.CanExecute.FirstAsync().Where(can => can).Do(async _ => await cmd.Execute()); public static bool GetCanExecute<TParam,TResult> cmd) => cmd.CanExecute.FirstAsync().Wait(); } 您可以使用此扩展方法,如下所示: command.ExecuteIfPossible().Subscribe(); 注意:你需要在最后调用Subscribe(),就像你需要它来调用Execute()一样,否则什么都不会发生. 或者如果你想使用async并等待: await command.ExecuteIfPossible(); 如果要检查命令是否可以执行,只需调用即可 command.GetCanExecute() (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |