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

时间:2017-04-01 02:29:12

标签: wpf reactiveui

我使用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));
        }
    }

看起来非常优雅,我喜欢它的清洁。但是当我尝试运行代码时,NullReferenceException获得WriteClFilesCommand,因为它尚未创建。

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

也许我可以创建一个单独的IObserable并让ReadClFilesCommand.CanExecuteWriteClFilesCommand.CanExecute进入,是否可能?

还有其他方法吗?

感谢。

1 个答案:

答案 0 :(得分:2)

我仍在使用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);

或者您可以使用主题通过

“播放”所有活动
        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);