Adding Child Controls to a Silverlight ListBox

Recently, I wrote an article Adding Child Controls to a ComboBox Items in Silverlight using C#. I got several questions on how to do the same in the ListBox control. Well, the answer is simple. Exactly same way.

This article demonstrates how to host various child controls within a ListBox control in Silverlight.

Adding child controls to a ComboBox is similar to adding any item to a ListBox. The ListBox.Items represents a collection of items of a ListBox. We can use ListBox.Items.Add() method to add an object to a ListBox. This object item can be a text, control or any other object.

The code snippet in Listing 12 adds a string, a Button, a TextBlock, a DateTime, a Rectangle, and a Panel with child controls to a ListBox.

// Add a String

listBox1.Items.Add("ListBox with Child Controls");

// Add a Button
btn = new Button();
btn.Height = 50;
btn.Width = 150;
btn.Content = "Click ME";
btn.Background = new SolidColorBrush(Colors.Orange);
btn.Foreground = new SolidColorBrush(Colors.Black);


// Create a TextBlock and Add it to ListBox

TextBlock textBlockItem = new TextBlock();
textBlockItem.TextAlignment = TextAlignment.Center;
textBlockItem.FontFamily = new FontFamily("Georgia");
textBlockItem.FontSize = 14;
textBlockItem.FontWeight = FontWeights.ExtraBold;
textBlockItem.Text = "Hello! I am a text block.";

// Add TextBlock to ListBox


// Add a DateTime to a ListBox

DateTime dateTime1 = new DateTime(2010, 10, 12, 8, 15, 55);

// Add a Rectangle to a ListBox

Rectangle rect1 = new Rectangle();
rect1.Width = 50;
rect1.Height = 50;
rect1.Fill = new SolidColorBrush(Colors.Red);


// Add a panel that contains child controls

TextBlock textBlock1 = new TextBlock();
textBlock1.TextAlignment = TextAlignment.Center;
textBlock1.Text = "Panel with child controls";

Ellipse ellipse1 = new Ellipse();
ellipse1.Width = 50;
ellipse1.Height = 50;
ellipse1.Fill = new SolidColorBrush(Colors.Green);

StackPanel ListBoxPanel = new StackPanel();
ListBoxPanel.Width = 200;
ListBoxPanel.Background = new SolidColorBrush(Colors.Yellow);


// Add Panel to ListBox

listBox1.SelectedIndex = 0;
listBox1.Padding = new Thickness(0);
listBox1.MaxWidth = 200;

The ListBox with child controls looks like following.


Using this same approach, you can add any controls to a ListBox. Also, keep in mind, these item controls can work independently. For example, if you need to add an event to the Button control in a ListBox, you may.