我有以下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
。我做错了什么?
答案 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);