如何在 ReactiveUI 的 ReactiveCommand 中为 canExecute 分配一个函数?

How to assign a function for canExecute in ReactiveCommand in ReactiveUI?

我最近开始学习响应式扩展,但不是 Rx 方面的专家。但是,我正在将以前编写的应用程序更改为 Reactive UI。但是,当我想将 RelayCommand 更改为 ReactiveCommand 时,我遇到了这个错误:

System.NotSupportedException: '索引表达式只支持常量。 我的 RelayCommand 定义如下:

DownloadCmd = new RelayCommand(async x=> await DownloadSubtitle(), CheckYoutubeLink);

我用反应命令改变了它如下:

var can = this.WhenAnyObservable(x=>Observable.Return(x.CheckYoutubeLink()));
DownloadCmd = ReactiveCommand.CreateFromTask(_ => DownloadSubtitle(),can);

不幸的是,它不起作用。换句话说,我的问题是如何将函数 (Func) 用于“canExecute”参数或行为类似于函数的东西。顺便说一句,我不喜欢使用属性而不是函数,因为我必须为我的命令编写许多属性。 我检查了这个 link: ReactiveUI: Using CanExecute with a ReactiveCommand然而,它对我帮助不大。

根据我在评论中所做的假设,解决方案可能如下所示:

    public ViewModel()
    {
        this
            .WhenAnyValue(x => x.CurrentLink)
            .Subscribe(_ => CheckYoutubeLink());

        var can = this
            .WhenAnyValue(x => x.IsLinkValid);

        DownloadCmd = ReactiveCommand.CreateFromTask(_ => DownloadSubtitle(), can);
    }


    public ICommand DownloadCmd { get; private set; }

    [Reactive]
    public string CurrentLink { get; set; }

    [Reactive]
    public bool IsLinkValid { get; set; }

    private Task<object> DownloadSubtitle()
    {
        // your logic here
    }

    private void CheckYoutubeLink()
    {
        // your logic here
        IsLinkValid = CurrentLink != null && CurrentLink.Contains("youtube");
    }

正如我所说,我不知道您的应用程序是什么样子,但只要您设置 link.

就必须调用 CheckYoutubeLink