观察反应列表和 属性

Observing a reactive list and property

我有以下 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 没有正确遵循可观察量。例如,当我添加 child 并将名称设置为 CanExecute 按预期更改为 true 的名称时,但是当我清除名称时 CanExecute 仍然保持 true。我做错了什么?

据我了解,

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

您可以通过多种方式解决此问题。我可能会这样做:

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