OpenLightGroup Blog

rss

Blogs from OpenLightGroup.net


Simple RadioButtonList and / or CheckBoxList in Silverlight Using a Behavior

A problem I have encountered frequently on recent projects is needing an ASP.Net style RadioButtonList or CheckBoxList inside on a Silverlight application. I have tried several approaches and had moderate success given the varying scenarios of each attempt. It finally came to a point that the problem had to be solved once and for all. So after discussing it with a few of the guys on my team and doing some extra reading tonight, I have found a solution that I feel is worth sharing. This post will be a step-by-step guide to using the ToogleButtonListBoxBehavior that I have created inside of the OpenLightGroup.Common Library.

To follow this tutorial you will need to download the latest version of the OpenLightGroup.Common Library and add a reference to the included dll file. We will also be using Microsoft Blend; however, the behavior can be added in Visual Studio just as other behaviors.

  1. Drop a ToggleButtonListBoxBehavior onto the ListBox.
    DropBehavior
  2. Bind the ListBox ItemsSource property to a ViewModel (You may also us a DomainDataSource or any way you would like to populate the Items of the ListBox).
    BindItemsSource ViewModelItemsBinding
  3. Create a new template for the ListBox ItemTemplate.
    EditTemplateCreateEmpty
  4. Create the template as a resource.
    CreateRadioButtonTemplate
  5. Create a StackPanel in the template and place a TextBlock and RadioButton in it  (You may also use a CheckBox or any other control that inherits from ToggleButton, see the notes at the end of the article).
    RadioButtonTemplateObjects
  6. Bind the Text property of the TextBlock to the property that you would like displayed.
    BindingItemNameRadioButtonList

 

That is all there is too it! Since this is still just a ListBox, you can customize it any way you like (at least any way you could any other ListBox). There are a few things to keep in mind documented in the following notes section.

Notes:

  • The ItemTemplate must contain a ToggleButton (this includes both RadioButton and CheckBox).
    • This means you cannot use the DisplayMemberPath on your ListBox.
  • Currently this behavior only uses the first ToggleButton it finds inside of the template.
  • Each item in the ListBox will have at least two event handlers attached to it to handle Checking and Unchecking etc. This may have a negative impact on performance in long lists.
  • If you are not finding the ToggleButtonListBoxBehavior in your assets lists, make you you have downloaded and added a reference to the latest OpenLightGroup.Common release.
  • If you are interested in how this behavior works you can view the source code here.




Comments are closed.