OnPropertyChanged parameter of INotifyPropertyChanged
Asked Answered
C

2

6

I am getting into MVVM and stumbled upon two versions of calling the OnPropertyChanged function shown in this MWE:

public class SampleModel : INotifyPropertyChanged
{
    private string _name;

    public string Name
    {
        get { return _name; }
        set
        {
            if (value == _name) return;
            _name = value;
            // Version 1
            OnPropertyChanged();
            // Version 2
            OnPropertyChanged(nameof(Name));
        }
    }

    #region INotifyPropertyChanged members
    public event PropertyChangedEventHandler PropertyChanged;

    [NotifyPropertyChangedInvocator]
    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
    #endregion
}

Why would I chose version 1 over version 2 and vice-versa?

Communistic answered 6/4, 2016 at 18:8 Comment(0)
T
8

The OnPropertyChanged(); call will automatically get the name of the classmember that called it, due to the [CallerMemberName] attribute.

The OnPropertyChanged(nameof(Name)); explicitly sends the property name as input parameter to the method.

So in your case the two calls would result in the exact same PropertyChanged invocation.

But the explicit call is useful if you change _name in a method or something like that, and want subscribers to be notified.

Torticollis answered 6/4, 2016 at 18:15 Comment(2)
I am accepting your answer because I didn't know what [CallerMemberName] does which you explained as well :)Communistic
That was needed here :) Do remember that the [CallerMemberName] attribute only works here because the string input is optional (string propertyName = null)Torticollis
G
5

Version 2 (with an explicit property name) is useful if the value of the property changes without calling the setter (as a side effect of some other operation) and you want to notify of that. In that case, the implicit CallerMemberName would not provide the correct property name.

This mainly comes up if you have a get-only property that does some sort of transformation of internal state to provide feedback. Every time that internal state changes, you notify that the get-only property (may) have changed. Personally I try to avoid this pattern, as it's easy to forget to notify when you make changes to the code later.

Gen answered 6/4, 2016 at 18:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.