This blog is subject the DISCLAIMER below.

Tuesday, February 13, 2007

INotifyPropertyChanged

If you know it, do not go through. This article just points to the importance of INotifyPropertyChanged and how to use it in our real world.


Almost of us use OOP technique so GUI in place and objects in other. And frequently GUI should response to objects updates.


I do not know how many lines I should write to update GUI when a specific object updates if I do not use INotifyPropertyChanged



So, let’s demonstrate how to use it

1-using System.ComponentModel;

2-Let’s your specific class inherit from INotifyPropertyChanged interface and expose its member public event PropertyChangedEventHandler PropertyChanged


3-Create your function to fire the event.


4-In each property you need to be in synchronization with GUI in your class in its setter call the function you have created in point 3


After following my instruction I managed to write these lines:


using System.ComponentModel; //point 1

class Person:INotifyPropertyChanged //point 2

{


string name;

public string Name
{


get { return name; }


set { name = value;

OnPropertyChanged("Name");//point 4


}


}


protected void OnPropertyChanged(string property)//point 3

{

if (PropertyChanged != null)

{

PropertyChanged(this,new PropertyChangedEventArgs(property));
}


}

public event PropertyChangedEventHandler PropertyChanged;//point 2


So, whenever person name has changed I’ll know that.


I’ll write a function in the Form class that uses this event and responses to it.

Person p = new Person("FCI-H", 1);

nameTxt.Text = p.Name;

p.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(p_PropertyChanged);

void p_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs
e)

{

switch (e.PropertyName)

{

case "Name":

nameTxt.Text = p.Name;

break;
}

}

So, whenever person name changed, Form textbox (nameTxt) will have the recent value, without writing additional code


You can download the full and commented sample from here


No comments: