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.
Here is VB.NET code.
' Add a String
ListBox1.Items.Add("ListBox with Child Controls")
' Add a Button
Dim btn As New Button()
btn.Height = 50
btn.Width = 150
btn.Content = "Click ME"
btn.Background = New SolidColorBrush(Colors.Orange)
btn.Foreground = New SolidColorBrush(Colors.Black)
ListBox1.Items.Add(btn)
' Create a TextBlock and Add it to ListBox
Dim textBlockItem As 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
ListBox1.Items.Add(textBlockItem)
' Add a DateTime to a ListBox
Dim dateTime1 As New DateTime(2010, 10, 12, 8, 15, 55)
ListBox1.Items.Add(dateTime1)
' Add a Rectangle to a ListBox
Dim rect1 As New Rectangle()
rect1.Width = 50
rect1.Height = 50
rect1.Fill = New SolidColorBrush(Colors.Red)
ListBox1.Items.Add(rect1)
' Add a panel that contains child controls
Dim textBlock1 As New TextBlock()
textBlock1.TextAlignment = TextAlignment.Center
textBlock1.Text = "Panel with child controls"
Dim ellipse1 As New Ellipse()
ellipse1.Width = 50
ellipse1.Height = 50
ellipse1.Fill = New SolidColorBrush(Colors.Green)
Dim ListBoxPanel As New StackPanel()
ListBoxPanel.Width = 200
ListBoxPanel.Background = New SolidColorBrush(Colors.Yellow)
ListBoxPanel.Children.Add(textBlock1)
ListBoxPanel.Children.Add(ellipse1)
' Add Panel to ListBox
ListBox1.Items.Add(ListBoxPanel)
ListBox1.SelectedIndex = 0
ListBox1.Padding = New Thickness(0)
ListBox1.MaxWidth = 200
The output 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.