观察被动列表和属性

时间:2016-01-03 21:37:50

标签: c# reactiveui

我有以下ViewModel

class MyViewModel
{      
    private string _name;

    public MyViewModel()
    {
        CommitChanges = ReactiveCommand.Create(Observable.When(
            this.ObservableForProperty(x => x.Name)
            .And(Childs.CountChanged)
            .Then((one, two) => !string.IsNullOrWhiteSpace(one.Value) && two > 0)));
        CommitChanges.Subscribe(_ => DoCommitChanges());
    }

    public IReactiveList Childs { get ; } = new ReactiveList<object>();

    public string Name
    {
        get { return _name; }
        set { this.RaiseAndSetIfChanged(ref _naam, value); }
    }

    public ReactiveCommand<object> CommitChanges { get; }

    private void DoCommitChanges() { ... }
}

CommitChanges命令的CanExecute未正确遵循observable。例如,当我添加一个孩子并将名称设置为CanExecute按预期更改为true时,但当我清除名称时,CanExecute仍会保留true。我做错了什么?

1 个答案:

答案 0 :(得分:2)

据我所知,

When / And / Then只会在两个序列产生值时生成一个值。因此,在Name更改之前,清除Childs.Count不会产生值。

有很多方法可以解决这个问题。我可能会这样做:

var nameHasValue = this.WhenAny(x => x.Name, x => !string.IsNullOrWhitespace(x.Value));

var isChildsEmpty = Childs.IsEmptyChanged.StartWith(Childs.IsEmpty);

var canCommit = nameHasValue
    .CombineLatest(isChildsEmpty, (hasName, isEmpty) => hasName && !isEmpty);

CommitChanges = ReactiveCommand.Create(canCommit);