WPF notifies PropertyChanged for Get property

I have INotifyPropertyChangedimplemented usingCallerMemberName

public event PropertyChangedEventHandler PropertyChanged;

protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
 if (PropertyChanged != null)
    {
        PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
}

Thus, it can be called in the installer of any property as - OnPropertyChanged(), which will notify you when the property of the event changes whenever it is set. This does not apply to getter-only properties. 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 great for DateOfBirth, but to notify Age changed, I have to remember OnPropertyChanged("Age")in the customizer DateOfBirth. I feel this makes the code difficult to maintain over time. If the new property is age dependent, it should also be notified in the DateOfBirth installer. Is there a better way to do this without calling OnPropertyChanged ("Age")?

+4
2

, Poma, , .

-, - PropertyChanged.

-

:

this.PropertyChanged += new PropertyChangedEventHandler(SubPropertyChanged);

:

private void SubPropertyChanged(object sender, PropertyChangedEventArgs e)
{
    if (e.PropertyName == "DateOfBirth")
    {
       OnPropertyChanged("Age");
    }
}

, - , .

+4

- OnPropertyChanged, . , .

private DateTime _dob;
public DateTime DateOfBirth
{
    get
    {
        return _dob;
    }
    private set
    {
        _dob = value;
        OnPropertyChanged();
    }
}

[DependsOnProperty("DateOfBirth")]
public int Age
{
    get
    {
        return DateTime.Today.Year - _dob.Year;
    }
}
-3

Source: https://habr.com/ru/post/1526916/


All Articles