【问题标题】:How to implement CanExecute in ReactiveCommand如何在 ReactiveCommand 中实现 CanExecute
【发布时间】:2018-04-16 09:31:44
【问题描述】:

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

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

我有一个像下面这样的 SignInViewMode 类..

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 绑定到视图中的按钮。我想实现 GoToNextCommand 的 CanExecute 功能(如果 UserName 或 PhoneNumber 属性中的任何一个为 null,则禁用 GoToNextCommand),但我不知道如何在 ReactiveProperty 中实现。

感谢任何帮助。

【问题讨论】:

    标签: xamarin.forms reactive-programming reactive-property


    【解决方案1】:

    感谢您使用我的图书馆。

    您可以从 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 ... });
    }
    

    【讨论】:

    • 谢谢一树。我还有一个关于 Reactive 属性的问题,我们如何使用 JSON 序列化这些属性。
    猜你喜欢
    • 2020-02-17
    • 1970-01-01
    • 1970-01-01
    • 2014-06-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多