Thursday, January 24, 2013

C# INotifyPropertyChanged Interface

How to implement INotifyPropertyChanged interface in C#?

The INotifyPropertyChanged interface is used and declared in the class level so all properties participated within the class can notify if the value has been changed. In WPF, this interface is very useful because most of the part of the XAML participated in the binding. In binding, it is important to notify the changes in the listener so the listener could update itself or even the UI.

Please visit Microsoft documentation for further details.

Below is an example code how to implement the INotifyPropertyChanged within the class. Let's call our class PropertyNotifier.

[Serializable]
public abstract class PropertyNotifier : INotifyPropertyChanged
{
    public PropertyNotifier()
        : base()
    {
    }
}

Now after you implemented the INotifyPropertyChanged in your class, you're are required to explicitly/implicitly implement the members of that interface. In INotifyPropertyChanged interface has one valuable member. It is an event called PropertyChanged. This event is being called inside the class every time the value of the property has been changed. See below how we implemented it.

[field: NonSerialized]
public event PropertyChangedEventHandler PropertyChanged;

After that, we need to create an additional method to be the bridge of calling this event. The most common name for that method is OnPropertyChanged as a standard naming convention of Microsoft. This method usually calls by each of the property of the class most likely in the set accessor and the one who actually call the PropertyChanged event. See below our implementation.

protected void OnPropertyChanged(string propertyName)
{
    if (!object.ReferenceEquals(this.PropertyChanged, null))
    {
        this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
}

Now if you're creating your own property within the class, you have to call the above's method and pass the actual literal property name on the method. See below our implementation.

private string __myProperty = string.Empty;
public string MyProperty
{
    get
    {
        return this.__myProperty;
    }
    set
    {
        this.__myProperty = value;
        this.OnPropertyChanged("MyProperty");
    }
}

You'll see that we created a new property named MyProperty. You will notice that in the set accessor, we called the OnPropertyChanged property just to notify the class that there is a value changed in the MyProperty property.

For the external library who are listening on the PropertyChanged event of the PropertyNotifier class, it will then automatically notify the value change.

Next topic is the inheritable PropertyNotifier object.

No comments:

Post a Comment

Place your comments and ideas