— New online course!  Getting Started with Azure DevOps — Special launch price 50% off —

Silverlight 4 Databound CheckBoxList and RadioButtonList Controls

by

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. 

<ItemsControl x:Name=”m_itemsControl” ItemsSource=”{Binding}”>
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <CheckBox Content=”{Binding Text}” IsChecked=”{Binding IsSelected, Mode=TwoWay}” />
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

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<ISelectableItem> 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


4 Responses to "Silverlight 4 Databound CheckBoxList and RadioButtonList Controls"
  1. Thanks!

    This was a big help.

    Is there a way to bind the Text, Value and IsSelected properties to arbitrary field names in my DataContext as you can with the Silverlight ComboxBox control (i.e., DisplayMemberPath, SelectedValuePath)?

    I couldn’t figure out how to do that with your control so I just supplied a DataContext that used the expected field names.

    Other than that. It works very well.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: