【问题标题】:Howto let ReactiveCommands observe their own IsExecuting observable如何让 Reactive Commands 观察自己的 IsExecuting observable
【发布时间】:2014-04-27 11:41:47
【问题描述】:

我的 ViewModel 中有几个命令,我想让每个按钮的 CanExecute 绑定到一个可观察到的忙,它被定义为当前没有任何按钮正在执行。

以下是我想出的,但显然它遇到了 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。

关于如何解决这个先有鸡还是先有蛋的问题有什么想法吗?观察 ViewModel(或 ViewModel 集合)忙碌状态的更好方法也将不胜感激:-)

【问题讨论】:

    标签: c# mvvm system.reactive reactiveui


    【解决方案1】:

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

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

    【讨论】:

    • 很好,很好用。从来没有想过这一点,我只会责怪“科目不好”——到处流传的口头禅:-)。此外,最后一行应包含.Subscribe(n =&gt; areAllAvailable.OnNext(n)) 以更新主题。
    • 主题不一定是“坏的”,它们只是不是很实用。它们实际上非常适合将现有代码适应 Rx,因为该代码也可能不是函数式的!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-19
    • 2021-08-30
    • 1970-01-01
    • 1970-01-01
    • 2021-08-29
    相关资源
    最近更新 更多