ReactiveCommand中如何实现CanExecute

How to implement CanExecute in ReactiveCommand

在我们的 Xamarin.Forms 应用程序中,我们使用 ReactiveProperty 框架(https://github.com/runceel/ReactiveProperty)。

请注意这里我们只使用 ReactiveProperty 而不是 ReactiveUI。

我有一个 SignInViewMode class 如下所示..

public class SignInPageViewModel
{
    // Constructor
    public SignInPageViewModel()
    {

    }

    // Reactive Properties
    public ReactiveProperty<string> PhoneNumber { get; set; } = new ReactiveProperty<string>();
    public ReactiveProperty<string> UserName { get; set; } = new ReactiveProperty<string>();
    //Commands
    public ReactiveCommand GoToNextCommand { get; set; } = new ReactiveCommand();
}

GoToNextCommand 绑定到视图中的 Button。我想实现 GoToNextCommand 的 CanExecute 功能(如果 UserName 或 PhoneNumber 属性 中的任何一个为 null,则禁用 GoToNextCommand),但我不知道如何在 ReactiveProperty 中实现此功能。

感谢任何帮助。

感谢您使用我的图书馆。

您可以从 IObservable 创建 ReactiveCommand 实例,如下所示。

GoToNextCommand = Observable.CombineLatest(
    PhoneNumber.Select(x => !string.IsNullOrEmpty(x)),
    UserName.Select(x => !string.IsNullOrEmpty(x)),
    (x, y) => x && y)
    .ToReactiveCommand();

并且可以一起使用验证功能。

// using System.ComponentModel.DataAnnotations;
[Required]
public ReactiveProperty<string> PhoneNumber { get; }
[Required]
public ReactiveProeprty<string> UserName { get; }  

public ReactiveCommand GoToNextCommand { get; }

public SignInPageViewModel()
{
    PhoneNumber = new ReactiveProperty<string>()
        .SetValidateAttribute(() => PhoneNumber);
    UserName = new ReactiveProperty<string>()
        .SetValidateAttribute(() => UserName);

    GoToNextCommand = Observable.CombineLatest(
        PhoneNumber.ObserveHasErrors.Inverse(),
        UserName.ObserveHasErrors.Inverse(),
        (x, y) => x && y)
        .ToReactiveCommand()
        .WithSubscribe(() => { ... do something ... });
}