有时我需要为相关属性提高propertychanged,如下所示:
public bool IsValid
{
get { return _isValid; }
set
{
if (value.Equals(_isValid)) return;
_isValid = value;
OnPropertyChanged("IsValid");
OnPropertyChanged("IsSavable");
}
}
我可以这样写:
public bool IsValid
{
get { return _isValid; }
set
{
if (value.Equals(_isValid)) return;
_isValid = value;
this.RaisePropertyChanged("IsValid");
this.RaisePropertyChanged("IsSavable");
}
}
基于保罗答案的代码:
public ViewModelBase()
{
Validator = new AlwaysTrueValidValidator<ViewModelBase>();
// logic for IsSavable
this.WhenAny(x => x.IsValid, x => x.IsDirty, x => x.IsBusy, (valid, dirty, busy) => valid.Value && dirty.Value && busy.Value == false)
.ToProperty(this, x => x.IsSavable, out _isSavable);
}
readonly ObservableAsPropertyHelper<bool> _isSavable;
public bool IsSavable
{
get { return _isSavable.Value; }
}
[UsedImplicitly]
public bool IsValid
{
get { return _isValid; }
set { this.RaiseAndSetIfChanged(ref _isValid, value); }
}
public void OnPropertyChanged(string property)
{
// ReSharper disable once ExplicitCallerInfoArgument
this.RaisePropertyChanged(property);
}
正如您所看到的,代码更清晰,所有内容都得到/设置并且逻辑在一个地方。
有更聪明的方法吗?是
答案 0 :(得分:5)
在ReactiveUI中,执行此操作的愿望意味着您正在做错(或者至少不是RxUI方式)。 IsSaveable与IsValid相关,您应该使用WhenAny
和ToProperty
来描述。也许你可以把它写成:
this.WhenAny(x => x.IsValid, x => x.IsChanged, (valid, changed) => valid.Value && changed.Value)
.ToProperty(this, x => x.IsSavable, out isSavable);