Silverlight 4 Databound CheckBoxList and RadioButtonList Controls

August 02, 2010

Last week I needed a CheckBoxList control and a RadioButtonList control for Silverlight 4.  I was surprised that they weren’t already part of the standard controls or the Silverlight Control Toolkit.

**RadioButtonList
**image

CheckboxList
image

Once I started to work on the controls, I realized that I didn’t know how to databind RadioButtons or databind Checkbox controls to a ViewModel in Silverlight.  The answer is to use the ItemsControl and the ItemsControl.ItemTemplate property.

                                   

If you’re going to wrap the checkboxes and radiobuttons in to a reusable control, the databinding expressions need to point to a constant type.  My controls bind to an interface called ISelectableItem that implements INotifyPropertyChanged.

public interface ISelectableItem : INotifyPropertyChanged
{
bool IsSelected { get; set; }
string Text { get; set; }
string Value { get; set; }       
}

This interface provides the Text to display in the list and also a boolean value to display whether the item is selected or not.  This allows me to bind the CheckboxList and RadioButtonList control to an instance of ObservableCollection and then all the rest of the work is done automatically through the viewmodel binding expressions.

Click here to view a running sample.
Click here to download the source code.

-Ben

-- Looking for help with your Silverlight architecture?  Worried about getting it right the first time?  Questions about how to unit test your Silverlight application?  Drop us a line: info@benday.com

Categories: silverlight-4