我找到了三种不同的解决方案来调用我的命令CanExecute
and Execute
像我之前在 ReactiveUI 6.5 中一样的方法:
Option 1
这与 6.5 版本中的调用相同,但我们需要显式地将命令转换为 ICommand:
if (((ICommand) command).CanExecute(null))
command.Execute().Subscribe();
Option 2
if(command.CanExecute.FirstAsync().Wait())
command.Execute().Subscribe()
或异步变体:
if(await command.CanExecute.FirstAsync())
await command.Execute()
Option 3
另一种选择是让我们InvokeCommand
扩展方法。
Observable.Start(() => {}).InvokeCommand(ViewModel, vm => vm.MyCommand);
这尊重命令的可执行性,如中提到的文档 https://docs.reactiveui.net/en/user-guide/commands/invoking-commands.html.
为了使它更舒适,我编写了一个小的扩展方法来提供ExecuteIfPossible
and a GetCanExecute
method:
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>(this ReactiveCommand<TParam, TResult> cmd) =>
cmd.CanExecute.FirstAsync().Wait();
}
您可以按如下方式使用此扩展方法:
command.ExecuteIfPossible().Subscribe();
注意:您需要Subscribe()
最后调用,就像您需要调用Execute()
,否则什么也不会发生。
或者,如果您想使用 async 和 wait:
await command.ExecuteIfPossible();
如果你想检查一个命令是否可以执行,只需调用
command.GetCanExecute()