How To: Binding a Property to a Label Control in a Windows Form

Note:  This technique works for 2005.  Hopefully there is an easier way in 2008:

Data Binding is a great mechanism for binding your control to a property in your form or user control so that the value changed in the control reflects the property and visa versa (the changed property reflects the control).

Let's say we have a property Title

private string _title = "Graph";
public string Title
 
{
  
get { return _title; }
  
set { _title = value;}
 }

and a Label control called lblTitle contained in a form

private Label lblTitle;

and we want to bind them.

The First step is to add the Title property to the data binding of the title label control.  This is accomplished by adding the name of the Title property to the DataBindings collection of the lblTitle control.

lblTitle.DataBindings.Add("Text", this, "Title");

The Add method takes (1) the name of the property on the control we want to bind to (2)  the class containing the property we are binding to (in this case the form)  and (3)  the name of the property.  This method should be called after InitializeComponent in the constructor.

You may be thinking this is all I need to do to bind to the control, but this method only changes the property if the label text changes.  In other words, it's a one-way binding.

In order to complete the two-way binding from the property back to the control, we need to do a bunch of stuff:

(1) We need to add an interface to our form called INotifyPropertyChanged

public class XYGraphControl : System.Windows.Forms.UserControl, INotifyPropertyChanged

(2)  We need to implement the interface event with the following line of code:

public event PropertyChangedEventHandler PropertyChanged;

(3)  We need to change our property Title set method to fire the event, passing the name of the property:

public string Title
{
  
get { return _title; }
 
set
   {
     
_title = value;
      
if (PropertyChanged != null)
        {
         
PropertyChanged(this, new PropertyChangedEventArgs("Title"));
   }
}

}

Now we are good to go.  We have a two-way binding between the Title property and the lblTitle control.

Hope this helps some struggling coders out there.  There is a pretty good example in MSDN

http://msdn2.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged.propertychanged.aspx

Happy Coding!