2014-04-27 65 views
5

我的ViewModel中有几个命令,我希望每个按钮的CanExecute都绑定到一个可观察的忙,它被定义为当前没有任何按钮正在执行。如何让ReactiveCommands观察他们自己的IsExecuting可观察的

以下是我想到的,但显然它会运行到NullReferenceException中。

busy = Observable.CombineLatest(this.PlayCommand.IsExecuting, this.PauseCommand.IsExecuting, (play, pause) => play && pause); 

this.PauseCommand = new ReactiveCommand(busy.Select(b => !b)); 
this.PlayCommand = new ReactiveCommand(busy.Select(b=> !b)); 

同样在ReactiveCommand的CanExecuteObservable属性是只读的,所以我必须先初始化命令定义的IObservable。

关于如何解决鸡和鸡蛋问题的任何想法?观察忙碌状态的视图模型(或的ViewModels的集合)的一种更好的方式将还赞赏:-)

回答

8

我将通过使用主题设置代理:

var areAllAvailable = new BehaviorSubject<bool>(true); 

PauseCommand = new ReactiveCommand(areAllAvailable); 
PlayCommand = new ReactiveCommand(areAllAvailable); 

Observable.CombineLatest(PauseCommand.IsExecuting, PlayCommand.IsExecuting, 
    (pa,pl) => !(pa || pl)) 
    .Subscribe(allAreAvailable); 
+0

大,很好地工作。从来没有想到这一点,我只会责怪'科目是坏' - 曼陀罗正在传播:-)。另外,最后一行应该包含'.Subscribe(n => areAllAvailable.OnNext(n))'来更新主题。 – Wouter

+0

受试者不一定是'坏',他们只是功能不够。它们实际上对于将现有代码适配到Rx非常有用,因为该代码可能不是功能性的! –

相关问题