21 February 2007

INotifyPropertyChanged Interface

Sometimes in my applications I use some binding mechanism. It helps me to build the huge forms. To show the way how it works at the begging I will create a small class Person which contains one property Surname linking with textbox.

public class Person

{

private string _surname;

public string Surname

{

get { return this._surname; }

set { this._surname = value; }

}


public Person(string surname)

{

this._surname = surname;

}

}

Next step is creating a new form on which will be placed the earlier mentioned textbox control. After that we have to simply override the OnLoad method.

protected override void OnLoad(EventArgs e)

{

base.OnLoad(e);

this.textBox1.DataBindings.Add("Text", this.p, "Surname");

}


Ok it is done. We can test it. Everything look quite nice, but what would happen if we change the p.Surname during application is running. Nothing. That's the problem the changes are not affected if we change the property Surname. To fix it we have to equip our Person class with INotifyPropertyChanged interface. This interface will add a new event to our class body. So if we have a new event We must use it.

public string Surname

{

get { return this._surname; }

set

{

this._surname = value;

if ( this.PropertyChanged != null)

this.PropertyChanged(this, new PropertyChangedEventArgs("Surname"));

}

}


Now when we start the application and we change Surname property we will find out that the textbox control has been changed too. That is what we wanted. Notice that PropertyChangedEventArgs constructor takes one string arg "PropertyName". This argument should be exact name of the property which is already changing.
Good luck

0 Comments:

Post a Comment

<< Home