Sometimes I need to raise propertychanged for a related property, like this:
public bool IsValid
{
get { return _isValid; }
set
{
if (value.Equals(_isValid)) return;
_isValid = value;
OnPropertyChanged("IsValid");
OnPropertyChanged("IsSavable");
}
}
I could write it like this:
public bool IsValid
{
get { return _isValid; }
set
{
if (value.Equals(_isValid)) return;
_isValid = value;
this.RaisePropertyChanged("IsValid");
this.RaisePropertyChanged("IsSavable");
}
}
Code based on Paul's answer:
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);
}
As you can see the code is a lot cleaner it's all get/set and the logic is in one place.
Is there a smarter way to do it? Yes