BlackWaspTM

This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

Windows Presentation Foundation
.NET 4.0+

WPF Data Binding - INotifyPropertyChanged

The ninety-third part of the Windows Presentation Foundation Fundamentals tutorial continues to look at data binding using the DataContext property. This article considers the INotifyPropertyChanged interface, which lets classes send notifications when property values are modified.

Raising Notifications

To fix the problem we need to implement INotifyPropertyChanged, which adds the PropertyChanged event to our data class. We then need to raise the event, passing the details of the properties that may now have different values. Let's begin by adding the interface.

INotifyPropertyChanged is found in the System.ComponentModel namespace, so add the following using directive to the top of the PersonalDetails class:

using System.ComponentModel;

Next, add the interface to the class declaration:

public class PersonalDetails : INotifyPropertyChanged

Implementing the interface requires that we declare the PropertyChanged event. Add the following to the class:

public event PropertyChangedEventHandler PropertyChanged;

Finally, let's add a method that can be called to raise the event and pass the name of the property that has been changed. To use the common convention, we'll call the method, "OnPropertyChanged".

When raising the event we need to pass an event arguments object of the type, PropertyChangedEventArgs. This holds the name of the property that has been amended. Only one property name can be passed at a time.

If you need to raise notifications for more than one property, you have two options. You can raise the event repeatedly, with one event for each property that has been amended. Alternatively, you can specify null or an empty string for the changed property name. This tells WPF to refresh the values for every data binding. Although the later approach is simpler, it can hurt performance if the properties are slow to read.

private void OnPropertyChanged(string property)
{
    if (PropertyChanged != null)
        PropertyChanged(this, new PropertyChangedEventArgs(property));
}

With the interface and helper method implemented, we can now update the FirstName and LastName properties so that they raise the notification that FullName may have changed.

public string FirstName
{
    get { return _firstName; }
    set
    {
        _firstName = value;
        OnPropertyChanged("FullName");
    }
}

public string LastName
{
    get { return _lastName; }
    set
    {
        _lastName = value;
        OnPropertyChanged("FullName");
    }
}

Run the program again and try updating the first and last names. You should see that the full name changes accordingly when the edited text box loses focus.

3 September 2014