在 ReactiveUI 绑定中,如何通过 2 个 ReactiveCommand 禁用 2 个按钮

in ReactiveUI binding, How to disable 2 buttons by 2 ReactiveCommand

我正在使用 ReactiveCommand 并将其绑定到一个按钮,并让该按钮在命令执行时自动禁用,效果很好。

现在我有 2 个 ReactiveCommand 和 2 个按钮,我希望在执行任何命令时禁用这 2 个按钮。我试过的是:

    public class MyClass
    {
        public MyClass()
        {
            ReadClFilesCommand = ReactiveCommand.Create(ReadClFiles, c.IsExecuting.Select(exe => !exe));            

            WriteClFilesCommand = ReactiveCommand.Create(WriteClFiles, ReadClFilesCommand.IsExecuting.Select(exe => !exe));
        }
    }

看起来很优雅,我喜欢它的干净。但是当我尝试 运行 代码时,我得到了 WriteClFilesCommandNullReferenceException 因为它还没有创建。

我想我需要先创建命令,然后再设置它的 CanExecute,但是 CanExecute 是只读的。

也许我可以创建一个单独的 IObserable 并让 ReadClFilesCommand.CanExecuteWriteClFilesCommand.CanExecute 进来,这可能吗?

还有其他方法吗?

谢谢。

我仍在使用 RxUI 6,所以我的语法有点不同,但我认为这两种方式都可以。 WhenAny* 助手是您最好的朋友,只要某些东西还不可用,或者如果您不知道它什么时候可用。只要您设置了它,那么设置这些命令就会引发 INotifyPropertyChanged 事件。

        IObservable<bool> canExecute =
            Observable.CombineLatest(
                this.WhenAnyObservable(x=> x.WriteClFilesCommand.IsExecuting),
                this.WhenAnyObservable(x => x.ReadClFilesCommand.IsExecuting))
                .Select(x => !x.Any(exec => exec));


        ReadClFilesCommand = 
            ReactiveCommand.CreateAsyncObservable(
                canExecute,
                ReadClFiles);

        WriteClFilesCommand = 
            ReactiveCommand.CreateAsyncObservable(
                canExecute,
                WriteClFiles);

或者您可以在 "play" 所有活动中使用主题

        BehaviorSubject<bool> canExecute = new BehaviorSubject<bool>(true);


        ReadClFilesCommand =
            ReactiveCommand.CreateAsyncObservable(
                canExecute,
                ReadClFiles);

        WriteClFilesCommand =
            ReactiveCommand.CreateAsyncObservable(
                canExecute,
                WriteClFiles);

        Observable.CombineLatest(
                WriteClFilesCommand.IsExecuting,
                ReadClFilesCommand.IsExecuting)
                .Select(x => !x.Any(exec => exec))
                .Subscribe(canExecute);