Wednesday, March 24, 2010

Creating a Checked ListBox in Silverlight with C#

I'm not sure if there is already a CheckedListBox control in Silverlight 4, but creating one manually is trivial enough that such a control may be unnecessary. Adding checkboxes to a ListBox is fairly easy in Silverlight 4 with a little bit of LINQ and some event handling.

In this example, we are going to be adding a list of names to a ListBox and figure out which names have a check next to them and which don't. We will also see how to set the IsChecked property of a CheckBox using code

string[] names = new[] {"Susan", "John", "Andrew", "Bob", "Raphael", "Sam"};

foreach (var name in names)
{
CheckBox checkBox = new CheckBox();
checkBox.Content = name;
checkBox.IsChecked = name.Contains('a'); // Place a check next to names containing an 'a'
//checkBox.Click += checkBox_Click;
ListBox1.Items.Add(checkBox);
}

It's seriously that simple. However, this probably isn't useful if you can't pull any data out of it. Finding which boxes are checked and which aren't is just as simple using LINQ.


string[] GetSelectedNames()
{
List selectedNames= new List();
var checkedCheckBoxes = from CheckBox checkBox in ListBox1.Items
where checkBox.IsChecked == true
select checkBox;
foreach (var name in checkedCheckBoxes)
{
selectedNames.Add(name.Content + Environment.NewLine);
}
return selectedNames.ToArray();
}


Here is a sample:
Get Microsoft Silverlight

No comments:

Post a Comment