Click here to Skip to main content
15,867,453 members
Articles / Programming Languages / C#
Article

Bind Better with INotifyPropertyChanged

Rate me:
Please Sign up or sign in to vote.
4.85/5 (28 votes)
5 Oct 2006CPOL5 min read 238.7K   5.1K   97   23
Data bind using INotifyPropertyChanged
Sample Image - DemoGUI.jpg

Introduction

Data binding is a fantastic feature of many components in the development world. The ability to connect the value of a property on a data object to some other property on another component can save a lot of time and code, if it works. .NET 2.0 brings many new features to the table and has cleaned up some old features. The INotifyPropertyChanged is a powerful new interface in the System.Component namespace.

The INotifyPropertyChanged interface provides a standard way to notify binding clients of a property value change. In the past, it was sometimes hit-or-miss as to when or whether a binding client would recognize a property change on a data object. If developers did not know how to bend the data bound client to their will, then a lot of nasty code often followed, along with some very foul words about hating data binding. Implementing INotifyPropertyChanged will help you keep your code clean and get the most out of the hard work that other developers have done to implement binding clients.

Special thanks to Jason Wergin for the base class code, and for pointing out this new and very useful interface.

A Quick Look at INotifyPropertyChanged

The interface itself, like most elegant solutions, is disgustingly simple. It has no properties and no methods. It has just one event, with a simple and perfectly clear name, PropertyChanged. The delegate for this event has two parameters. The first, of course, is the sender, and the second, the PropertyChangedEventArgs, which has one property, PropertyName. As I said, “Simple”.

A Simple Base Class

Indeed the interface is so simple that you could write a very useful base class to speed the implementation of this interface across any data objects you would like to bind. Below is a simple base class that we use in some of the products that I am working on.

C#
public abstract class NotifyProperyChangedBase : INotifyPropertyChanged
    {
        #region INotifyPropertyChanged Members
        public event PropertyChangedEventHandler PropertyChanged;
        #endregion
        #region methods
        protected bool CheckPropertyChanged<T>
		(string propertyName, ref T oldValue, ref T newValue)
        {
            if (oldValue == null && newValue == null)
            {
                return false;
            }

            if ((oldValue == null && newValue != null) || !oldValue.Equals((T)newValue))
            {
                oldValue = newValue;
                FirePropertyChanged(propertyName);              
                return true;                
            }

            return false;
        }

        protected void FirePropertyChanged(string propertyName)
        {
            if (this.PropertyChanged != null)
            {
                this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }

        #endregion
    }

The class wraps the logic to see if a value is changing in a generic method, and also provides a standard method call for raising the PopertyChanged event, all very simple and very useful. Now implementing the INotifyPropertyChanged interface is as simple as inheriting this base class and calling these two methods when needed.

Now Let’s See an Example

In this example, we are going to create two data objects, one that implements INotifyPropertyChanged and one that does not. Then we will bind instances of them to list boxes and see how differently they behave (see download for demo code).

  1. Open up Visual Studio 2005 and create a new C# Windows Forms project and name it INotifyDemo.
  2. In the same solution, create a new C# class library project and name it MyComponentModel. This project just represents the framework library that we should put our useful NotifyProperyChangedBase class in.
  3. Now add a new class to the MyComponentModel project and name it NotifyProperyChangedBase. The base class code laid out in the previous section of this article should be copied into the class file and saved.
  4. Right click on the MyComponentModel project in the solution explorer and click the Build menu item to compile the project.

Now we are going to create the two data objects. These are going to be simple person objects, one will use our new base class thereby implementing INotifyPropertyChanged, and the other will be a plain old regular object.

Add a new class to the INotifyDemo project and name it RegularPerson. Put the following code in the class:

C#
class RegularPerson
    {
        private string _firstName;

        public string FirstName
        {
            get { return _firstName; }
            set { _firstName = value; }
        }

        private string _lastName;

        public string LastName
        {
            get { return _lastName; }
            set { _lastName = value; }
        }

        public string DisplayName
        {
            get { return _firstName + " " + _lastName; }
        }
    }

As you can see, it is a very vanilla data class that holds the name of a person.

Now we need to create a similar class that inherits our useful base class which implements the INotifyPropertyChanged interface. So, add another new class to the INotifyDemo project and name it NotifiablePerson. Put the following code in the class:

C#
class NotifiablePerson : MyComponentModel.NotifyProperyChangedBase
    {
        private string _firstName;

        public string FirstName
        {
            get { return _firstName; }
            set 
            {
                if (this.CheckPropertyChanged<string>
			("FirstName", ref _firstName, ref value))
                {
                    this.DisplayNameChanged();
                }
            }
        }

        private string _lastName;

        public string LastName
        {
            get { return _lastName; }
            set 
            {
                if (this.CheckPropertyChanged<string>
			("LastName", ref _lastName, ref value))
                {
                    this.DisplayNameChanged();
                }
            }
        }

        public string DisplayName
        {
            get { return _firstName + " " + _lastName; }
        }

        private void DisplayNameChanged()
        {
            this.FirePropertyChanged("DisplayName");
        }
    }

In this class, we inherit the NotifyPropertyChangedBase class. In the setters for the FirstName and LastName properties, we use the generic CheckPropertyChanged method to set the class attribute that holds the property value and we raise the PropertyChanged event if needed. Also, if the property value indeed changes, then the read only property DisplayName also changes. So, we use the FirePropertyChanged method to inform the binding client of the change. Simple enough.

Now drag two groupboxes, two listboxes, and four textboxes onto Form1 and arrange them so the form looks like this:

Image 2

With the form laid out, you need to wire up event handlers for the form Load event and for the TextChanged event on each of the text boxes. For each of the listboxes, set the DisplayMemeber property to DisplayName and the ValueMemeber property to FirstName. Now add code to Form1 until it looks like this:

C#
public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            LoadRegularList();

            LoadNotiList();            
        }

        private void LoadRegularList()
        {
            System.ComponentModel.BindingList<RegularPerson> rl = 
			new System.ComponentModel.BindingList<RegularPerson>();

            RegularPerson rp = rl.AddNew();
            rp.FirstName = "John";
            rp.LastName = "Smith";

            RegularPerson rp2 = rl.AddNew();
            rp2.FirstName = "Joe";
            rp2.LastName = "Shmoe";

            listBox1.DataSource = rl;
        }

        private void LoadNotiList()
        {
            System.ComponentModel.BindingList<NotifiablePerson> nl = 
			new System.ComponentModel.BindingList<NotifiablePerson>();
            
            NotifiablePerson np = nl.AddNew();
            np.FirstName = "Jane";
            np.LastName = "Doe";

            NotifiablePerson np2 = nl.AddNew();
            np2.FirstName = "Mary";
            np2.LastName = "Smith";

            listBox2.DataSource = nl;
        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            if (listBox1.SelectedItem != null)
            {
                ((RegularPerson)listBox1.SelectedItem).FirstName = textBox1.Text;
            }
        }

        private void textBox2_TextChanged(object sender, EventArgs e)
        {
            if (listBox1.SelectedItem != null)
            {
                ((RegularPerson)listBox1.SelectedItem).LastName = textBox2.Text;
            }
        }

        private void textBox3_TextChanged(object sender, EventArgs e)
        {
            if (listBox2.SelectedItem != null)
            {
                ((NotifiablePerson)listBox2.SelectedItem).FirstName = textBox3.Text;
            }
        }

        private void textBox4_TextChanged(object sender, EventArgs e)
        {
            if (listBox2.SelectedItem != null)
            {
                ((NotifiablePerson)listBox2.SelectedItem).LastName = textBox4.Text;
            }
        }
    }

On this form, we now have two lists whose item values we can manipulate. The top section edits the FirstName and LastName of the selected RegularPerson item in the list and the bottom section edits the same properties of the selected NotifiablePerson item in its list.

Build and run INotifyDemo.

Try selecting an item in the “Regular Person” list and typing a new name into either the “First Name” or “Last Name” text boxes. You will notice that the item text in the list does not change even though the underlying value has changed. You can set a break point on one of the TextChanged events and see that the value has indeed changed.

Now select an item in the “Notifiable Person” list and type a new name into either the “First Name” or “Last Name” text boxes. TA-DA! The item text in the list changes immediately. The binding client, in this case the list box, was informed via the PropertyChanged event and did its job perfectly; no need to write ugly code to get the listbox item text to refresh.

Conclusion

You can expect this kind of good behavior from all binding clients when you implement INotifyPropertyChanged. Create a good solid base class (like the one in this article) that implements the interface and use it on any object you wish to bind. It will allow you to take full advantage of binding clients and save you from having to write unnecessary and ugly code.

NOTE: We also used the generic BindingList; this is also recommended when binding collections to clients.

History

  • 5th October, 2006: Initial post

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionTypo: NotifyProperyChangedBase Pin
Roland Illig24-Jul-16 0:21
Roland Illig24-Jul-16 0:21 
Questionnice work! Pin
Member 1129842627-Jul-15 4:33
Member 1129842627-Jul-15 4:33 
QuestionMy vote of 5 Pin
sbarnes2-Apr-14 8:47
sbarnes2-Apr-14 8:47 
GeneralMy vote of 5 Pin
Bujar Muliqi23-Jan-13 22:11
Bujar Muliqi23-Jan-13 22:11 
GeneralMy vote of 5 Pin
nellob23-Sep-12 21:34
nellob23-Sep-12 21:34 
GeneralMy vote of 5 Pin
ado_e13-May-12 20:53
ado_e13-May-12 20:53 
GeneralOne of the best article to study INotifyProperty Changed Pin
Theingi Win15-Mar-11 18:36
Theingi Win15-Mar-11 18:36 
GeneralSimplier Version Pin
MetalKid00719-May-10 4:17
MetalKid00719-May-10 4:17 
GeneralRe: Simplier Version Pin
ke4vtw28-Jun-11 6:05
ke4vtw28-Jun-11 6:05 
GeneralRe: Simplier Version Pin
vahapdemir10-Jan-12 5:12
vahapdemir10-Jan-12 5:12 
QuestionWhere is the this.PropertyChanged set ? Pin
jobo708-Feb-10 11:47
jobo708-Feb-10 11:47 
AnswerRe: Where is the this.PropertyChanged set ? Pin
quetzilla19-Mar-10 11:48
quetzilla19-Mar-10 11:48 
GeneralGood but did the same thing with less coding. Pin
alan9329-Jan-10 8:32
alan9329-Jan-10 8:32 
GeneralGreat article (5) , and a question about threads... Pin
ggraham41229-Oct-09 10:54
ggraham41229-Oct-09 10:54 
GeneralA different layout Pin
stixoffire17-Jun-09 1:25
stixoffire17-Jun-09 1:25 
GeneralRe: A different layout Pin
ke4vtw6-Apr-11 7:21
ke4vtw6-Apr-11 7:21 
QuestionHow to implement INotifyPropertyChanged right? Pin
jbe822418-Apr-09 11:00
jbe822418-Apr-09 11:00 
GeneralThank you great example Pin
Tailslide30-Jul-08 18:06
Tailslide30-Jul-08 18:06 
For some reason there is a lack of real world examples of INotifyPropertyChanged.
I found this very helpful, thank you.
Questionhow about asp.net ? Pin
dsmportal26-Jul-08 15:46
dsmportal26-Jul-08 15:46 
AnswerRe: how about asp.net ? Pin
Xmen Real 10-Jul-10 6:40
professional Xmen Real 10-Jul-10 6:40 
QuestionHow about this version? Pin
Chris Khoo27-Mar-07 2:58
Chris Khoo27-Mar-07 2:58 
QuestionEvent fired twice Pin
pinx9-Oct-06 22:51
pinx9-Oct-06 22:51 
AnswerRe: Event fired twice Pin
pconverse10-Oct-06 5:19
pconverse10-Oct-06 5:19 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.