2017-04-01 64 views
2

我使用ReactiveCommand并将其绑定到一个按钮,并让该按钮在执行命令时自动禁用,它工作得很好。在ReactiveUI绑定,如何禁用2个按钮2 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,这有可能吗?

还有其他方法可以做到吗?

谢谢。

回答

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); 
+1

我用你的第二个解决方案中使用受“玩”所有的活动和它的作品,甚至自动关闭3个按键,:-) – Felix