【问题标题】:in ReactiveUI binding, How to disable 2 buttons by 2 ReactiveCommand在 ReactiveUI 绑定中,如何通过 2 ReactiveCommand 禁用 2 个按钮
【发布时间】:2017-04-01 13:58:59
【问题描述】:

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

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

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

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

还有其他方法吗?

谢谢。

【问题讨论】:

    标签: wpf reactiveui


    【解决方案1】:

    我仍在使用 RxUI 6,所以我的语法有点不同,但我认为这两种方式中的任何一种都可以。 WhenAny* helpers 是您最好的朋友,当某些东西尚不可用或您不知道它何时可用时。只要您进行了设置,那么设置这些命令就会引发 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);
    

    【讨论】:

    • 我使用了你的第二个解决方案,它可以工作,甚至可以自动禁用 3 个按钮,:-)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-02
    • 1970-01-01
    • 2023-03-23
    • 1970-01-01
    相关资源
    最近更新 更多