XAML ListBox

This article shows how to create and use XAML ListBox control in your applications.
  • 4401

Items controls are controls that have children. Any control with collection falls in this category.  A ListBox control is an Items control. ListBox is a collection of ListBoxItems.

Creating a ListBox

The following code creates a ListBox. As you can see from this code, we can set the height, widht, alignment, and background of the ListBox.

<ListBox Height="100" Width="120" HorizontalAlignment="Center"
  VerticalAlignment="Top" Background="LightGray">

</ListBox>

Adding ListBox Items

The following code creates a ListBox with 4 ListBox items.

<Window xmlns="http://schemas.microsoft.com/winfx/avalon/2005"
 xmlns:x="
http://schemas.microsoft.com/winfx/xaml/2005">


<ListBox Height="100" Width="120" HorizontalAlignment="Center"
  VerticalAlignment="Top" Background="LightGray">
   <ListBoxItem >1. C#
Corner</ListBoxItem>
   <ListBoxItem >2. .NET Heaven</ListBoxItem>
   <ListBoxItem >3. Longhorn Corner</ListBoxItem>
   <ListBoxItem >4. VB.NET Heaven</ListBoxItem>
</ListBox>

</Window>

The outout looks like Figure 1.

 ListBoxImg1.gif

Figure 1. ListBox with items

Changing ListBox Item Properties

You can also set ListBox item properties. For example, this code sets the background color of ListBox items.

 <ListBox Height="100" Width="120" HorizontalAlignment="Center"
  VerticalAlignment="Top" Background="LightGray">
   <ListBoxItem Foreground="Green">1. C# Corner</ListBoxItem>
   <ListBoxItem Foreground="Red">2. .NET Heaven</ListBoxItem>
   <ListBoxItem Foreground="Black">3. Longhorn Corner</ListBoxItem>
   <ListBoxItem Foreground="Blue">4. VB.NET Heaven</ListBoxItem>
</ListBox>

The output looks like Figure 2.

 ListBoxImg2.gif

Figure 2. ListBox with colored items

ListBox with CheckBoxes

The following code adds CheckBox items to a ListBox.

 <ListBox Height="100" Width="120">
   <CheckBox ID="Item1">1. C# Corner</CheckBox>
 <CheckBox ID="Item2">2. VB.NET Heaven</CheckBox>
 <CheckBox ID="Item3">3. Longhorn Corner</CheckBox>
 <CheckBox ID="Item4">4. .NET Heaven</CheckBox>   
</ListBox>

The output looks like Figure 3.

 ListBoxImg3.gif

Figure 3. ListBox with check boxes

ListBox with Image CheckBox

The following code adds a CheckBox with an image to a ListBox.

 <ListBox Height="200" Width="120">
 <CheckBox ID="Item1"><Image Source="C:\butterfly.jpg"/></CheckBox>
 <CheckBox ID="Item2">2. VB.NET Heaven</CheckBox>
 <CheckBox ID="Item3">3. Longhorn Corner</CheckBox>
 <CheckBox ID="Item4">4. .NET Heaven</CheckBox>   
</ListBox>

The output looks like Figure 4.

 ListBoxImg4.gif

Figure 4. ListBoxItem with Imaged CheckBox 

Further Readings
 
You may also want to read these related articles.
Ask Your Question 
 
Got a programming related question? You may want to post your question here
 

 

 

 

 

© 2020 DotNetHeaven. All rights reserved.