I have the INotifyPropertyChanged
implemented using CallerMemberName
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
So this could be called in the setter of any property as - OnPropertyChanged()
which would notify property changed event whenever it is being set. This is not the case for a property a getter only. For example,
private DateTime _dob;
public DateTime DateOfBirth
{
get
{
return _dob;
}
private set
{
_dob = value;
OnPropertyChanged();
OnPropertyChanged("Age");
}
}
public int Age
{
get
{
return DateTime.Today.Year - _dob.Year;
}
}
OnPropertyChanged()
works fine for DateOfBirth, but to notify Age changed, I should remember to call OnPropertyChanged("Age")
within the setter of DateOfBirth
. I feel this makes the code difficult to maintain over time. If a new property depends on Age, that also needs to be Notified in the setter of DateOfBirth. Is there a better way to do this without calling OnPropertyChanged("Age")?