Sunday, November 28, 2010

Binding TextBlock, ListBox, RadioButtons to Enums

Introduction
This post demonstrates different ways to bind WPF controls to an enum property so that changing the selected item on the control automatically updates the value of the property. Examples for a ListBox, ComboBox, a group of RadioButtons and a ListBox of RadioButtons is shown. A way to convert the enum value to a user-friendly string is also shown.

Using the Code
You have an enum property such as the following:

private enum State
{
   Virginia,
   WestVirginia,
   NorthCarolina,
   SouthCarolina
};

and a UserControl with the property such as the following:

private States _state;
public  States State
{
   get { return _state; }
   set { _state = value; }
}

and you want to hook up a combo box, a list box or a panel of radio buttons to the property to allow the user to select a specific value.

1 - Create the User Control
We want to bind to the property in our UserControl, so we will have to change it fire the PropertyChanged event.
So we do the following:
Add the System.ComponentModel namespace:

using System.ComponentModel;

Add the INotifyPropertyChanged interface to our UserControl and implement the interface by adding a PropertyChanged event:

public partial class UserControl1 : UserControl, INotifyPropertyChanged
{
   public event PropertyChangedEventHandler PropertyChanged;

Change the property that raises the PropertyChanged event when the value changes:

private States _state;
public States State
{
   get { return _state; }
   set
   {
       if ( _state != value )
       {
           _state = value;
           if ( PropertyChanged != null )
           {
                PropertyChanged( this,
new PropertyChangedEventArgs( "State" ));
           }
       }
   }
}

Make it pretty.

If you have multiple properties, this snippet of code takes a lot of coding. We can separate this out by creating a convenience function to check and call the PropertyChanged event.

Read more: Codeproject