[英]How do I make a direct call to ReactiveCommand.Execute() in ReactiveUI 7 correct?
I'm trying to convert my project from ReactiveUI 6.5 to version 7. In the old version I called 我正在尝试将我的项目从ReactiveUI 6.5转换为版本7.在旧版本中我调用了
// var command = ReactiveCommand.Create...;
// ...
if(command.CanExecute(null))
command.Execute(null);
in order to execute a command from my code behind. 为了从我的代码后面执行命令。
Now the CanExecute method is no longer available and replaced with a property of IObservable<bool>
. 现在,CanExecute方法不再可用,并替换为IObservable<bool>
的属性。 Is the CanExecute Observable automatically called if I just make a call to Execute().Subscribe()
or must I call it explicitly? 如果我只是调用Execute().Subscribe()
是否会自动调用CanExecute Observable.Subify Execute().Subscribe()
或者我必须显式调用它吗?
For now I replaced the above code with 现在我用上面的代码替换了
command.Execute().Subscribe();
I found three different solutions to call my command's CanExecute
and Execute
methods like I could before in ReactiveUI 6.5: 我找到了三种不同的解决方案来调用我的命令的CanExecute
和Execute
方法,就像我之前在ReactiveUI 6.5中那样:
Option 1 选项1
This is equal to the call in version 6.5, but we need to explicitly convert the command to an ICommand: 这等于6.5版本中的调用,但我们需要将命令显式转换为ICommand:
if (((ICommand) command).CanExecute(null))
command.Execute().Subscribe();
Option 2 选项2
if(command.CanExecute.FirstAsync().Wait())
command.Execute().Subscribe()
or the async variant: 或异步变体:
if(await command.CanExecute.FirstAsync())
await command.Execute()
Option 3 选项3
Another option is to make us of the InvokeCommand
extension method. 另一个选择是使我们使用InvokeCommand
扩展方法。
Observable.Start(() => {}).InvokeCommand(ViewModel, vm => vm.MyCommand);
This respects the command's executability, like mentioned in the documentation . 这尊重命令的可执行性,如文档中所述。
In order to make it more comfortable I've written a small extension method to provide a ExecuteIfPossible
and a GetCanExecute
method: 为了让它更舒服,我编写了一个小扩展方法来提供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>(this ReactiveCommand<TParam, TResult> cmd) =>
cmd.CanExecute.FirstAsync().Wait();
}
You can use this extension method as follows: 您可以使用此扩展方法,如下所示:
command.ExecuteIfPossible().Subscribe();
Note: You need the Subscribe()
call at the end, just like you need it for the call to Execute()
, otherwise nothing will happen. 注意:你需要在最后调用Subscribe()
,就像你需要它来调用Execute()
,否则什么都不会发生。
Or if you want to use async and await: 或者如果你想使用async并等待:
await command.ExecuteIfPossible();
If you want to check if a command can be executed, just call 如果要检查命令是否可以执行,只需调用即可
command.GetCanExecute()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.