WPF ListBox Tutorial

The ListBox class in C# and WPF represents a ListBox control. WPF ListBox is a collection of ListBoxItem. The code example in this tutorial demo how to add list box items, add items to a ListBox, remove items from a ListBox, and bind a ListBox to a data source.

WPF ListBox Code Example

Download attached project and open in Visual Studio and run it. Several part of the XAML file may be commented. Uncomment the part you like to run.

Introduction to WPF ListBox Control 

The XAML ListBox element represents a ListBox control.

  1. <ListBox></ListBox>  

The Width and Height properties represent the width and the height of a ListBox. The Name property represents the name of the control, which is a unique identifier of a control. The Margin property tells the location of a ListBox on the parent control. The HorizontalAlignment and VerticalAlignment properties are used to set horizontal and vertical alignments.

The following code snippet sets the name, height, and width of a ListBox control. The code also sets horizontal alignment to left and vertical alignment to top.

  1. <ListBox Margin="10,10,0,13" Name="listBox1" HorizontalAlignment="Left" VerticalAlignment="Top" Width="194" Height="200" />  

Add Items to a ListBox Control 

A ListBox control is a collection of ListBoxItem. The following code example adds a collection of items to a ListBox control.

  1. <ListBox Margin="10,10,0,13" Name="listBox1" HorizontalAlignment="Left" VerticalAlignment="Top" Width="194" Height="200">  
  2.     <ListBoxItem Content="Coffie"></ListBoxItem>  
  3.     <ListBoxItem Content="Tea"></ListBoxItem>  
  4.     <ListBoxItem Content="Orange Juice"></ListBoxItem>  
  5.     <ListBoxItem Content="Milk"></ListBoxItem>  
  6.     <ListBoxItem Content="Iced Tea"></ListBoxItem>  
  7.     <ListBoxItem Content="Mango Shake"></ListBoxItem>  
  8. </ListBox>  

The above code generates Figure 1.

 ListBox In WPF
Figure 1. ListBox with items

 

Dynamically Adding ListBox Items

 

In the previous section, we saw how to add items to a ListBox at design-time from XAML. We can add items to a ListBox from the code.

Let's change our UI and add a TextBox and a button control to the page. The XAML code for the TextBox and Button controls look like the following,

  1. <TextBox Height="23" HorizontalAlignment="Left" Margin="8,14,0,0" Name="textBox1" VerticalAlignment="Top" Width="127" />  
  2. <Button Height="23" Margin="140,14,0,0" Name="button1" VerticalAlignment="Top" HorizontalAlignment="Left" Width="76" Click="button1_Click"> Add Item </Button>  

The final UI looks like Figure 2.

ListBox In WPF
Figure 2.

On button click event handler, we add the contents of TextBox to the ListBox by calling ListBox.Items.Add method. The following code adds TextBox contents to the ListBox items.

  1. privatevoid button1_Click(object sender, RoutedEventArgs e) {  
  2.     listBox1.Items.Add(textBox1.Text);  
  3. }  

On button click event handler, we add the content of TextBox to the ListBox by calling ListBox.Items.Add method.

Now, if you enter text in the TextBox and click Add Item button, it will add contents of the TextBox to the ListBox.

Adding ListBox items dynamically
Figure 3. Adding ListBox items dynamically

 

Deleting ListBox Items 

We can use ListBox.Items.Remove or ListBox.Items.RemoveAt method to delete an item from the collection of items in the ListBox. The RemoveAt method takes the index of the item in the collection.

Now, we modify our application and add a new button called Delete Item. The XAML code for this button looks like below.

  1. <Button Height="23" Margin="226,14,124,0" Name="DeleteButton" VerticalAlignment="Top" Click="DeleteButton_Click"> Delete Item</Button>  

The button click event handler looks like the following. On this button click, we find the index of the selected item and call ListBox.Items.RemoveAt method as following.

  1. privatevoid DeleteButton_Click(object sender, RoutedEventArgs e) {  
  2.     listBox1.Items.RemoveAt(listBox1.Items.IndexOf(listBox1.SelectedItem));  
  3. }  

 

Formatting ListBox Items 

The Foreground and Background attributes of ListBoxItem represents the background and foreground colors of the item. The following code snippet sets background and foreground color of a ListBoxItem.

  1. <ListBoxItem Background="LightCoral" Foreground="Red" Content="Coffie"></ListBoxItem>  

The FontFamily, FontSize, and FontWeight are used to set a font of a ListBoxItem. The following code snippet sets font verdana, size 12, and bold of a ListBoxItem.

  1. <ListBoxItem Background="LightCoral" Foreground="Red" Content="Coffie" FontFamily="Verdana" FontSize="12" FontWeight="Bold"></ListBoxItem>  

I set the following properties of ListBoxItems.

  1. <ListBoxItem Background="LightCoral" Foreground="Red" Content="Coffie" FontFamily="Verdana" FontSize="12" FontWeight="Bold"></ListBoxItem>  
  2. <ListBoxItem Background="LightGray" Foreground="Black" Content="Tea" FontFamily="Georgia" FontSize="14" FontWeight="Bold"></ListBoxItem>  
  3. <ListBoxItem Background="LightBlue" Foreground="Purple" Content="Orange Juice" FontFamily="Verdana" FontSize="12" FontWeight="Bold"></ListBoxItem>  
  4. <ListBoxItem Background="LightGreen" Foreground="Green" Content="Milk" FontFamily="Georgia" FontSize="14" FontWeight="Bold"></ListBoxItem>  
  5. <ListBoxItem Background="LightBlue" Foreground="Blue" Content="Iced Tea" FontFamily="Verdana" FontSize="12" FontWeight="Bold"></ListBoxItem>  
  6. <ListBoxItem Background="LightSlateGray" Foreground="Orange" Content="Mango Shake" FontFamily="Georgia" FontSize="14" FontWeight="Bold"></ListBoxItem>  

The new ListBox looks like Figure 4. 

Formatted ListBox 
Figure 4. Formatted ListBox

 

Load Image in a WPF ListBox 

We can put any controls inside a ListBoxItem such as an image and text. To display an image side by side some text, I simply put an Image and TextBlock control within a StackPanel. The Image.Source property takes the name of the image you would like to display in the Image control and TextBlock.Text property takes a string that you would like to display in the TextBlock.

The following code snippet adds an image and text to a ListBoxItem.

  1. <ListBoxItem Background="LightCoral" Foreground="Red" FontFamily="Verdana" FontSize="12" FontWeight="Bold">  
  2.     <StackPanel Orientation="Horizontal">  
  3.         <Image Source="coffie.jpg" Height="30"></Image>  
  4.         <TextBlock Text="Coffie"></TextBlock>  
  5.     </StackPanel>  
  6. </ListBoxItem>  

After changing my code for all 5 ListBoxItems, the ListBox looks like Figure 5.

ListBoxItems with Image and text
Figure 5. ListBoxItems with Image and text

 

ListBox with CheckBoxes 

If you put a CheckBox control inside ListBoxItems, you generate a ListBox control with checkboxes in it. The CheckBox can host controls within it as well. For instance, we can put an image and text block as the content of a CheckBox.

The following code snippet adds a CheckBox with an image and text to a ListBoxItem.

  1. <ListBoxItem Background="LightCoral" Foreground="Red" FontFamily="Verdana" FontSize="12" FontWeight="Bold">  
  2.     <CheckBox Name="CoffieCheckBox">  
  3.         <StackPanel Orientation="Horizontal">  
  4.             <Image Source="coffie.jpg" Height="30"></Image>  
  5.             <TextBlock Text="Coffie"></TextBlock>  
  6.         </StackPanel>  
  7.     </CheckBox>  
  8. </ListBoxItem>  

I changed the code of ListBoxItems and added the following CheckBoxes to the items. As you may see, I have set the name of the CheckBoxes using Name property. If you need to access these CheckBoxes, you may access them in the code using their Name property.

  1. <ListBoxItem Background="LightCoral" Foreground="Red" FontFamily="Verdana" FontSize="12" FontWeight="Bold">  
  2.     <CheckBox Name="CoffieCheckBox">  
  3.         <StackPanel Orientation="Horizontal">  
  4.             <Image Source="coffie.jpg" Height="30"></Image>  
  5.             <TextBlock Text="Coffie"></TextBlock>  
  6.         </StackPanel>  
  7.     </CheckBox>  
  8. </ListBoxItem>  
  9. <ListBoxItem Background="LightGray" Foreground="Black" FontFamily="Georgia" FontSize="14" FontWeight="Bold">  
  10.     <CheckBox Name="TeaCheckBox">  
  11.         <StackPanel Orientation="Horizontal">  
  12.             <Image Source="tea.jpg" Height="30"></Image>  
  13.             <TextBlock Text="Tea"></TextBlock>  
  14.         </StackPanel>  
  15.     </CheckBox>  
  16. </ListBoxItem>  
  17. <ListBoxItem Background="LightBlue" Foreground="Purple" FontFamily="Verdana" FontSize="12" FontWeight="Bold">  
  18.     <CheckBox Name="OrangeJuiceCheckBox">  
  19.         <StackPanel Orientation="Horizontal">  
  20.             <Image Source="OrangeJuice.jpg" Height="40"></Image>  
  21.             <TextBlock Text="OrangeJuice"></TextBlock>  
  22.         </StackPanel>  
  23.     </CheckBox>  
  24. </ListBoxItem>  
  25. <ListBoxItem Background="LightGreen" Foreground="Green" FontFamily="Georgia" FontSize="14" FontWeight="Bold">  
  26.     <CheckBox Name="MilkCheckBox">  
  27.         <StackPanel Orientation="Horizontal">  
  28.             <Image Source="Milk.jpg" Height="30"></Image>  
  29.             <TextBlock Text="Milk"></TextBlock>  
  30.         </StackPanel>  
  31.     </CheckBox>  
  32. </ListBoxItem>  
  33. <ListBoxItem Background="LightBlue" Foreground="Blue" FontFamily="Verdana" FontSize="12" FontWeight="Bold">  
  34.     <CheckBox Name="IcedTeaCheckBox">  
  35.         <StackPanel Orientation="Horizontal">  
  36.             <Image Source="IcedTea.jpg" Height="30"></Image>  
  37.             <TextBlock Text="Iced Tea"></TextBlock>  
  38.         </StackPanel>  
  39.     </CheckBox>  
  40. </ListBoxItem>  
  41. <ListBoxItem Background="LightSlateGray" Foreground="Orange" FontFamily="Georgia" FontSize="14" FontWeight="Bold">  
  42.     <CheckBox Name="MangoShakeCheckBox">  
  43.         <StackPanel Orientation="Horizontal">  
  44.             <Image Source="MangoShake.jpg" Height="30"></Image>  
  45.             <TextBlock Text="Mango Shake"></TextBlock>  
  46.         </StackPanel>  
  47.     </CheckBox>  
  48. </ListBoxItem>  

Now, the new ListBox looks like Figure 6.

ListBox with CheckBoxes 
Figure 6. ListBox with CheckBoxes

 

Data Binding In ListBox Control 

Before I discuss data binding in general, I must confess, Microsoft experts have made a big mess related to data-binding in .NET 3.0 and 3.5. Instead of making things simpler, they have made them complicated. Maybe they have some bigger plans in the future but so far I have seen binding using dependency objects and properties, LINQ and DLINQ, and WCF and ASP.NET Web Services and it all looks like a big mess. It's not even close to the ADO.NET model we had in .NET 1.0 and 2.0. I hope they clean up this mess in the near future.

When it comes to data binding, we need to first understand the data. Here is a list of ways a data can be consumed from -

  • objects
  • a relational database such as SQL Server
  • a XML file
  • other controls

Data Binding with Objects

The ItemsSource property of ListBox is used to bind a collection of IEnumerable such as an ArrayList to the ListBox control.

  1. // Bind ArrayList with the ListBox  
  2. LeftListBox.ItemsSource = LoadListBoxData();  
  3. privateArrayList LoadListBoxData() {  
  4.     ArrayList itemsList = newArrayList();  
  5.     itemsList.Add("Coffie");  
  6.     itemsList.Add("Tea");  
  7.     itemsList.Add("Orange Juice");  
  8.     itemsList.Add("Milk");  
  9.     itemsList.Add("Mango Shake");  
  10.     itemsList.Add("Iced Tea");  
  11.     itemsList.Add("Soda");  
  12.     itemsList.Add("Water");  
  13.     return itemsList;  
  14. }  

Sample - Transferring data from one ListBox to Another

We've seen many requirements where a page has two ListBox controls and left ListBox displays a list of items and using a button we can add items from the left ListBox and add them to the right side ListBox and using the remove button we can remove items from the right side ListBox and add them back to the left side ListBox.

This sample shows how we can move items from one ListBox to another. The final page looks like Figure 7. The Add button adds the selected item to the right side ListBox and removes from the left side ListBox. The Remove button removes the selected item from the right side ListBox and adds back to the left side ListBox.

ListBox In WPF
Figure 7

The following XAML code generates two ListBox control and two Button controls.

  1. <ListBox Margin="11,13,355,11" Name="LeftListBox" />  
  2. <ListBox Margin="0,13,21,11" Name="RightListBox" HorizontalAlignment="Right" Width="216" />  
  3. <Button Name="AddButton" Height="23" Margin="248,78,261,0" VerticalAlignment="Top" Click="AddButton_Click">Add >></Button>  
  4. <Button Name="RemoveButton" Margin="248,121,261,117" Click="RemoveButton_Click"><< Remove</Button>  

On the Window loaded event, we create and load data items to the ListBox by setting the ItemsSource property to an ArrayList.

  1. privatevoid Window_Loaded(object sender, RoutedEventArgs e) {  
  2.     // Get data from somewhere and fill in my local ArrayList  
  3.     myDataList = LoadListBoxData();  
  4.     // Bind ArrayList with the ListBox  
  5.     LeftListBox.ItemsSource = myDataList;  
  6. }  
  7. ///<summary>  
  8. /// Generate data. This method can bring data from a database or XML file  
  9. /// or from a Web service or generate data dynamically  
  10. ///</summary>  
  11. ///<returns></returns>  
  12. privateArrayList LoadListBoxData() {  
  13.     ArrayList itemsList = newArrayList();  
  14.     itemsList.Add("Coffie");  
  15.     itemsList.Add("Tea");  
  16.     itemsList.Add("Orange Juice");  
  17.     itemsList.Add("Milk");  
  18.     itemsList.Add("Mango Shake");  
  19.     itemsList.Add("Iced Tea");  
  20.     itemsList.Add("Soda");  
  21.     itemsList.Add("Water");  
  22.     return itemsList;  
  23. }  

On Add button click event handler, we get the value and index of the selected item in the left side ListBox and add that to the right side ListBox and remove that item from the ArrayList, which is our data source.The ApplyBinding method simply removes the current binding of the ListBox and rebinds with the updated ArrayList.

  1. privatevoid AddButton_Click(object sender, RoutedEventArgs e) {  
  2.     // Find the right item and it's value and index  
  3.     currentItemText = LeftListBox.SelectedValue.ToString();  
  4.     currentItemIndex = LeftListBox.SelectedIndex;  
  5.     RightListBox.Items.Add(currentItemText);  
  6.     if (myDataList != null) {  
  7.         myDataList.RemoveAt(currentItemIndex);  
  8.     }  
  9.     // Refresh data binding  
  10.     ApplyDataBinding();  
  11. }  
  12. ///<summary>  
  13. /// Refreshes data binding  
  14. ///</summary>  
  15. privatevoid ApplyDataBinding() {  
  16.     LeftListBox.ItemsSource = null;  
  17.     // Bind ArrayList with the ListBox  
  18.     LeftListBox.ItemsSource = myDataList;  
  19. }  

Similarly, on the Remove button click event handler, we get the selected item text and index from the right side ListBox and add that to the ArrayList and remove from the right side ListBox.

  1. privatevoid RemoveButton_Click(object sender, RoutedEventArgs e)   
  2. {  
  3.     // Find the right item and it's value and index  
  4.     currentItemText = RightListBox.SelectedValue.ToString();  
  5.     currentItemIndex = RightListBox.SelectedIndex;  
  6.     // Add RightListBox item to the ArrayList  
  7.     myDataList.Add(currentItemText);  
  8.     RightListBox.Items.RemoveAt(RightListBox.Items.IndexOf(RightListBox.SelectedItem));  
  9.     // Refresh data binding  
  10.     ApplyDataBinding();  
  11. }  

Data Binding with a Database

We use Northwind.mdf database that comes with SQL Server. In our application, we will read data from Customers table. The Customers table columns looks like Figure 9.

ListBox In WPF
Figure 9

We will read ContactName, Address, City, and Country columns in a WPF ListBox control. The final ListBox looks like Figure 10.

ListBox In WPF
Figure 10

Now let's look at our XAML file. We create resources DataTemplate type called listBoxTemplate. A data template is used to represent data in a formatted way. The data template has two dock panels where the first panel shows the name and the second panel shows address, city, and country columns by using TextBlock controls.

  1. <Window.Resources>  
  2.     <DataTemplate x:Key="listBoxTemplate">  
  3.         <StackPanel Margin="3">  
  4.             <DockPanel>  
  5.                 <TextBlock FontWeight="Bold" Text="Name:" DockPanel.Dock="Left" Margin="5,0,10,0" />  
  6.                 <TextBlock Text="" />  
  7.                 <TextBlock Text="{Binding ContactName}" Foreground="Green" FontWeight="Bold" />  
  8.             </DockPanel>  
  9.             <DockPanel>  
  10.                 <TextBlock FontWeight="Bold" Text="Address:" Foreground="DarkOrange" DockPanel.Dock="Left" Margin="5,0,5,0" />  
  11.                 <TextBlock Text="{Binding Address}" />  
  12.                 <TextBlock Text=", " />  
  13.                 <TextBlock Text="{Binding City}" />  
  14.                 <TextBlock Text=", " />  
  15.                 <TextBlock Text="{Binding Country}" />  
  16.             </DockPanel>  
  17.         </StackPanel>  
  18.     </DataTemplate>  
  19. </Window.Resources>  

Now we add a ListBox control and set its ItemsSource property as the first DataTable of the DataSet and set ItemTemplate to the resource defined above.

  1. <ListBox Margin="17,8,15,26" Name="listBox1" ItemsSource="{Binding Tables[0]}" ItemTemplate="{StaticResource listBoxTemplate}" />  

Now in our code behind, we define the following variables.

  1. publicSqlConnection connection;  
  2. publicSqlCommand command;  
  3. string sql = "SELECT ContactName, Address, City, Country FROM Customers";  
  4. string connectionString = @ "Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\NORTHWND.MDF;Integrated Security=True;Connect Timeout=30;User Instance=True";  

Now on Windows_Loaded method, we call BindData method and in BindData method, we create a connection, data adapter, and fill the DataSet using SqlDataAdapter.Fill() method.

  1. privatevoid Window_Loaded(object sender, RoutedEventArgs e) {  
  2.     BindData();  
  3. }  
  4. privatevoid BindData() {  
  5.     DataSet dtSet = newDataSet();  
  6.     using(connection = newSqlConnection(connectionString)) {  
  7.         command = newSqlCommand(sql, connection);  
  8.         SqlDataAdapter adapter = newSqlDataAdapter();  
  9.         connection.Open();  
  10.         adapter.SelectCommand = command;  
  11.         adapter.Fill(dtSet, "Customers");  
  12.         listBox1.DataContext = dtSet;  
  13.     }  
  14. }  

Data Binding with XML

Now let's look at how we can bind XML data to a ListBox control. The XmlDataProvider is used to bind XML data in WPF.

Here is an XmlDataProvider defined in XAML that contains books data.The XML data is defined within the x:Data tag.

  1. <XmlDataProvider x:Key="BooksData" XPath="Inventory/Books">  
  2.     <x:XData>  
  3.         <Inventory xmlns="">  
  4.             <Books>  
  5.                 <Book Category="Programming">  
  6.                     <Title>A Programmer's Guide to ADO.NET</Title>  
  7.                     <Summary>Learn how to write database applications using ADO.NET and C#. </Summary>  
  8.                     <Author>Mahesh Chand</Author>  
  9.                     <Publisher>APress</Publisher>  
  10.                 </Book>  
  11.                 <Book Category="Programming">  
  12.                     <Title>Graphics Programming with GDI+</Title>  
  13.                     <Summary>Learn how to write graphics applications using GDI+ and C#. </Summary>  
  14.                     <Author>Mahesh Chand</Author>  
  15.                     <Publisher>Addison Wesley</Publisher>  
  16.                 </Book>  
  17.                 <Book Category="Programming">  
  18.                     <Title>Visual C#</Title>  
  19.                     <Summary>Learn how to write C# applications. </Summary>  
  20.                     <Author>Mike Gold</Author>  
  21.                     <Publisher>APress</Publisher>  
  22.                 </Book>  
  23.                 <Book Category="Programming">  
  24.                     <Title>Introducing Microsoft .NET</Title>  
  25.                     <Summary>Programming .NET </Summary>  
  26.                     <Author>Mathew Cochran</Author>  
  27.                     <Publisher>APress</Publisher>  
  28.                 </Book>  
  29.                 <Book Category="Database">  
  30.                     <Title>DBA Express</Title>  
  31.                     <Summary>DBA's Handbook </Summary>  
  32.                     <Author>Mahesh Chand</Author>  
  33.                     <Publisher>Microsoft</Publisher>  
  34.                 </Book>  
  35.             </Books>  
  36.         </Inventory>  
  37.     </x:XData>  
  38. </XmlDataProvider>  

To bind an XmlDataProvider, we set the Source property inside the ItemsSource of a ListBox to the x:Key of XmlDataProvider and XPath is used to filter the data. In the ListBox.ItemTempate, we use Binding property.

  1. <ListBox Width="400" Height="300" Background="LightGray">  
  2.     <ListBox.ItemsSource>  
  3.         <Binding Source="{StaticResource BooksData}" XPath="*[@Category='Programming'] " />  
  4.     </ListBox.ItemsSource>  
  5.     <ListBox.ItemTemplate>  
  6.         <DataTemplate>  
  7.             <StackPanel Orientation="Horizontal">  
  8.                 <TextBlock Text="Title: " FontWeight="Bold" />  
  9.                 <TextBlock Foreground="Green">  
  10.                     <TextBlock.Text>  
  11.                         <Binding XPath="Title" />  
  12.                     </TextBlock.Text>  
  13.                 </TextBlock>  
  14.             </StackPanel>  
  15.         </DataTemplate>  
  16.     </ListBox.ItemTemplate>  
  17. </ListBox>  

The output of the above code looks like Figure 11.

ListBox In WPF
Figure 11

Data Binding with Controls

The last data binding type we will see is how to provide data exchange between a ListBox and other controls using data binding in WPF.

We will create an application that looks like Figure 12. In Figure 12, I have a ListBox with a list of colors, a TextBox, and a Canvas. When we pick a color from the ListBox, the text of TextBox and color of Canvas changes dynamically to the color selected in the ListBox and this is possible to do all in XAML without writing a single line of code in the code behind file.

ListBox In WPF
Figure 12.

The XAML code of the page looks like following.

  1. <StackPanel Orientation="Vertical">  
  2.     <TextBlock Margin="10,10,10,10" FontWeight="Bold"> Pick a color from below list </TextBlock>  
  3.     <ListBox Name="mcListBox" Height="100" Width="100" Margin="10,10,0,0" HorizontalAlignment="Left">  
  4.         <ListBoxItem>Orange</ListBoxItem>  
  5.         <ListBoxItem>Green</ListBoxItem>  
  6.         <ListBoxItem>Blue</ListBoxItem>  
  7.         <ListBoxItem>Gray</ListBoxItem>  
  8.         <ListBoxItem>LightGray</ListBoxItem>  
  9.         <ListBoxItem>Red</ListBoxItem>  
  10.     </ListBox>  
  11.     <TextBox Height="23" Name="textBox1" Width="120" Margin="10,10,0,0" HorizontalAlignment="Left">  
  12.         <TextBox.Text>  
  13.             <Binding ElementName="mcListBox" Path="SelectedItem.Content" />  
  14.         </TextBox.Text>  
  15.     </TextBox>  
  16.     <Canvas Margin="10,10,0,0" Height="200" Width="200" HorizontalAlignment="Left">  
  17.         <Canvas.Background>  
  18.             <Binding ElementName="mcListBox" Path="SelectedItem.Content" />  
  19.         </Canvas.Background>  
  20.     </Canvas>  
  21. </StackPanel>  

If you look at the TextBox XAML code, you will see the Binding within the TextBox.Text property, which sets the binding from TextBox to another control and another control ID is ElementName and another control's property is Path. So in the below code, we are setting the SelectedItem.Content property of ListBox to TextBox.Text property.

  1. <TextBox.Text>  
  2.     <Binding ElementName="mcListBox" Path="SelectedItem.Content" />  
  3. </TextBox.Text>  

Now the same applies to the Canvas.Background property, where we set it to the SelectedItem.Content of the ListBox. Now, every time you select an item in the ListBox, the TextBox.Text and Canvas.Background properties are set to that selected item in the ListBox.

  1. <Canvas.Background>  
  2.     <Binding ElementName="mcListBox" Path="SelectedItem.Content" />  
  3. </Canvas.Background>  

 

Sorting a ListBox Items


You can add SortDescriptions to the WPF ListBox items to sort them in ascending or descending orders.

The following code snippet sorts a ListBox's contents. You can write this code on a button click or any other event where you would like to sort your ListBox items. 
  1. listBox1.Items.SortDescriptions.Add(new System.ComponentModel.SortDescription("Content", System.ComponentModel.ListSortDirection.Ascending))   

Summary

In this article, I discussed how to create and use a ListBox control available in WPF. We saw how we can add items to a ListBox, change item properties, add images add checkboxes. At the end of this article, we saw how data binding works in ListBox and how to bind ListBox with data coming from objects, database, and other controls.

I hope you enjoyed this article. All feedback and critiques are most welcome. Feel free to post them at the bottom of this article.