ListBox in WPF

This tutorial shows you how to create and use a ListBox control in WPF and XAML. The tutorial also covers styling and formatting, add images, checkboxes, and data binding in a ListBox contrtol.
  • 10383
 

WPF ListBox Tutorial

This tutorial shows you how to create and use a ListBox control available in Windows Presentation Foundation (WPF)

Sample code

Open the attached solution in Visual Studio 2008 and change the XAML file name in app.xaml to the file name you would like to run.

Introduction

The ListBox tag represents a ListBox control in XAML.

<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.

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


Adding ListBox Items

A ListBox control hosts a collection of ListBoxItem. The following code snippet adds items to a ListBox control.

   <ListBox Margin="10,10,0,13" Name="listBox1" HorizontalAlignment="Left"
         VerticalAlignment="Top" Width="194" Height="200">
        <ListBoxItem Content="Coffie"></ListBoxItem>
        <ListBoxItem Content="Tea"></ListBoxItem>
        <ListBoxItem Content="Orange Juice"></ListBoxItem>
        <ListBoxItem Content="Milk"></ListBoxItem>
        <ListBoxItem Content="Iced Tea"></ListBoxItem>
        <ListBoxItem Content="Mango Shake"></ListBoxItem>
    </ListBox>

The above code generates Figure 1.

WPFListBoxImage1.gif

Figure 1. ListBox with items

Adding ListBox Items Dynamically

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 following:

    <TextBox Height="23" HorizontalAlignment="Left" Margin="8,14,0,0" 
                 Name="textBox1" VerticalAlignment="Top" Width="127" />
        <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.

WPFListBoxImage2.gif

Figure 2.

On button click event handler, we add the content of TextBox to the ListBox by calling ListBox.Items.Add method. The following code adds TextBox contents to the ListBox items. 
 
    Private Sub button1_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
        listBox1.Items.Add(textBox1.Text)
    End Sub


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.

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.

<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 following. On this button click, we find the index of the selected item and call ListBox.Items.RemoveAt method as following.

    Private Sub DeleteButton_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
        listBox1.Items.RemoveAt()
(listBox1.Items.IndexOf(listBox1.SelectedItem))
    End Sub


Formatting and Styling

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.

<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.

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

I set the following properties of ListBoxItems.

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

The new ListBox looks like Figure 4.

WPFListBoxImage4.gif

Figure 4. Formatted ListBox

Displaying Images in a 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.

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

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

WPFListBoxImage5.gif

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 content of a CheckBox.

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

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

I change the code of ListBoxItems and add 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.

<ListBoxItem Background="LightCoral" Foreground="Red"
             FontFamily="Verdana" FontSize="12" FontWeight="Bold">               
        <CheckBox Name="CoffieCheckBox">
            <StackPanel Orientation="Horizontal">
            <Image Source="coffie.jpg" Height="30"></Image>
            <TextBlock Text="Coffie"></TextBlock>
        </StackPanel>
    </CheckBox>
</
ListBoxItem>
<
ListBoxItem Background="LightGray" Foreground="Black"
             FontFamily="Georgia" FontSize="14" FontWeight="Bold">
    <CheckBox Name="TeaCheckBox">
        <StackPanel Orientation="Horizontal">
            <Image Source="tea.jpg" Height="30"></Image>
            <TextBlock Text="Tea"></TextBlock>
        </StackPanel>
    </CheckBox>
</
ListBoxItem>
<
ListBoxItem Background="LightBlue" Foreground="Purple"
             FontFamily="Verdana" FontSize="12" FontWeight="Bold">
    <CheckBox Name="OrangeJuiceCheckBox">
        <StackPanel Orientation="Horizontal">
            <Image Source="OrangeJuice.jpg" Height="40"></Image>
            <TextBlock Text="OrangeJuice"></TextBlock>
        </StackPanel>
    </CheckBox>
</
ListBoxItem>
<
ListBoxItem Background="LightGreen" Foreground="Green"
             FontFamily="Georgia" FontSize="14" FontWeight="Bold">
    <CheckBox Name="MilkCheckBox">
        <StackPanel Orientation="Horizontal">
            <Image Source="Milk.jpg" Height="30"></Image>
            <TextBlock Text="Milk"></TextBlock>
        </StackPanel>
    </CheckBox>
</
ListBoxItem>
<
ListBoxItem Background="LightBlue" Foreground="Blue"
             FontFamily="Verdana" FontSize="12" FontWeight="Bold">
    <CheckBox Name="IcedTeaCheckBox">
        <StackPanel Orientation="Horizontal">
            <Image Source="IcedTea.jpg" Height="30"></Image>
            <TextBlock Text="Iced Tea"></TextBlock>
        </StackPanel>
    </CheckBox>
</
ListBoxItem>
<
ListBoxItem Background="LightSlateGray" Foreground="Orange"
             FontFamily="Georgia" FontSize="14" FontWeight="Bold">
    <CheckBox Name="MangoShakeCheckBox">
        <StackPanel Orientation="Horizontal">
            <Image Source="MangoShake.jpg" Height="30"></Image>
            <TextBlock Text="Mango Shake"></TextBlock>
        </StackPanel>
    </CheckBox>
</
ListBoxItem>

Now, the new ListBox looks like Figure 6.

WPFListBoxImage6.gif

Figure 6. ListBox with CheckBoxes

Data Binding

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. May be they have some bigger plans in 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 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 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 IEnuemerable such as an ArrayList to the ListBox control. 
 
' Bind ArrayList with the ListBox
   Private Function LoadListBoxData() As ArrayList
        Dim itemsList As ArrayList = New ArrayList()
        itemsList.Add("Coffie")
        itemsList.Add("Tea")
        itemsList.Add("Orange Juice")
        itemsList.Add("Milk")
        itemsList.Add("Mango Shake")
        itemsList.Add("Iced Tea")
        itemsList.Add("Soda")
        itemsList.Add("Water")
        Return itemsList
    End
Function

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.

WPFListBoxImage7.gif

Figure 7

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

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


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

    Private Sub Window_Loaded(ByVal sender As Object, ByVal e As RoutedEventArgs)
       
' Get data from somewhere and fill in my local ArrayList
        myDataList = LoadListBoxData()
       
' Bind ArrayList with the ListBox
        LeftListBox.ItemsSource = myDataList
    End
Sub


'/ <summary>
    '/ Generate data. This method can bring data from a database or XML file
    '/ or from a Web service or generate data dynamically
    '/ </summary>
    '/ <returns></returns>
    Private Function LoadListBoxData() As ArrayList
        Dim itemsList As ArrayList = New ArrayList()
        itemsList.Add("Coffie")
        itemsList.Add("Tea")
        itemsList.Add("Orange Juice")
        itemsList.Add("Milk")
        itemsList.Add("Mango Shake")
        itemsList.Add("Iced Tea")
        itemsList.Add("Soda")
        itemsList.Add("Water")
        Return itemsList
    End
Function


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.

   Private Sub AddButton_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
       
' Find the right item and it's value and index
        currentItemText = LeftListBox.SelectedValue.ToString()
        currentItemIndex = LeftListBox.SelectedIndex
         RightListBox.Items.Add(currentItemText)
        If Not myDataList Is Nothing
Then
            myDataList.RemoveAt(currentItemIndex)
        End
If

        ' Refresh data binding
        ApplyDataBinding()
    End
Sub

     '/ <summary>
    '/ Refreshes data binding
    '/ </summary>
    Private Sub ApplyDataBinding()
        LeftListBox.ItemsSource =
Nothing
        ' Bind ArrayList with the ListBox
        LeftListBox.ItemsSource = myDataList
    End
Sub


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.

  Private Sub RemoveButton_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
       
' Find the right item and it's value and index
        currentItemText = RightListBox.SelectedValue.ToString()
        currentItemIndex = RightListBox.SelectedIndex
       
' Add RightListBox item to the ArrayList
        myDataList.Add(currentItemText)
       RightListBox.Items.RemoveAt(RightListBox.Items.IndexOf(RightListBox.SelectedItem))

         ' Refresh data binding
        ApplyDataBinding()
    End
Sub

Data Binding with a Database

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


WPFListBoxImage9.gif

Figure 9 
 
We will read ContactName, Address, City, and Country columns in a WPF ListBox control. The final ListBox looks.
 
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 first panel shows the name and second panel shows address, city, and country columns by using TextBlock controls.


<Window.Resources>
    <DataTemplate x:Key="listBoxTemplate">
        <StackPanel Margin="3">
            <DockPanel >
                <TextBlock FontWeight="Bold" Text="Name:"
                  DockPanel.Dock="Left"
                  Margin="5,0,10,0"/>
                <TextBlock Text="  " />
                <TextBlock Text="{Binding ContactName}" Foreground="Green" FontWeight="Bold" />
            </DockPanel>
            <DockPanel >
                <TextBlock FontWeight="Bold" Text="Address:" Foreground ="DarkOrange" 
                  DockPanel.Dock
="Left"
                  Margin="5,0,5,0"/>
                <TextBlock Text="{Binding Address}" />
                 <TextBlock Text=", " />
                <TextBlock Text="{Binding City}" />
                 <TextBlock Text=", " />
                <TextBlock Text="{Binding Country}" />
            </DockPanel>
        </StackPanel>
    </DataTemplate>
</
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.

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

Now in our code behind, we define following variables.

 Public connection As SqlConnection
    Public command As SqlCommand
    Dim sql As String = "SELECT ContactName, Address, City, Country FROM Customers"
    Dim connectionString As String =
"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.

   Private Sub Window_Loaded(ByVal sender As Object, ByVal e As RoutedEventArgs)
        BindData()
    End
Sub
 
    Private Sub BindData()
        Dim dtSet As DataSet = New DataSet()
Imports (connection = New SqlConnection(connectionString))
{
        command = New SqlCommand(sql, connection)
        Dim adapter As SqlDataAdapter = New SqlDataAdapter()
        connection.Open()
        adapter.SelectCommand = command
        adapter.Fill(dtSet, "Customers")
        listBox1.DataContext = dtSet
}
    End
Sub

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.


<XmlDataProvider x:Key="BooksData" XPath="Inventory/Books">
    <x:XData>
        <Inventory xmlns="">
            <Books>
                <Book Category="Programming" >
                    <Title>A Programmer's Guide to ADO.NET</Title>
                    <Summary>Learn how to write database applications using ADO.NET and C#.
                   
</Summary>
                    <Author>Mahesh Chand</Author>
                    <Publisher>APress</Publisher>
                </Book>
                <Book Category="Programming" >
                    <Title>Graphics Programming with GDI+</Title>
                    <Summary>Learn how to write graphics applications using GDI+ and C#.
                   
</Summary>
                    <Author>Mahesh Chand</Author>
                    <Publisher>Addison Wesley</Publisher>
                </Book>
                <Book Category="Programming" >
                    <Title>Visual C#</Title>
                    <Summary>Learn how to write C# applications.
                   
</Summary>
                    <Author>Mike Gold</Author>
                    <Publisher>APress</Publisher>
                </Book>
                <Book Category="Programming" >
                    <Title>Introducing Microsoft .NET</Title>
                    <Summary>Programming .NET
                   
</Summary>
                    <Author>Mathew Cochran</Author>
                    <Publisher>APress</Publisher>
                </Book>
                <Book Category="Database" >
                    <Title>DBA Express</Title>
                    <Summary>DBA's Handbook
                   
</Summary>
                    <Author>Mahesh Chand</Author>
                    <Publisher>Microsoft</Publisher>
                </Book>
            </Books>          
       
</Inventory>
    </x:XData>
</
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.
 

<ListBox Width="400" Height="300" Background="LightGray">
    <ListBox.ItemsSource>
        <Binding Source="{StaticResource BooksData}"
       XPath="*[@Category='Programming'] "/>
    </ListBox.ItemsSource>
 
    <ListBox.ItemTemplate>
        <DataTemplate>
            <StackPanel Orientation="Horizontal">
                <TextBlock Text="Title: " FontWeight="Bold"/>
                <TextBlock Foreground="Green"  >
                    <TextBlock.Text>
                       
<Binding XPath="Title"/>
                    </TextBlock.Text>                      
               
</TextBlock>                    
          
</StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
</
ListBox>

The output of the above code looks like Figure 11.

WPFListBoxImage11.gif

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.
 
The XAML code of the page looks like following.


<StackPanel Orientation="Vertical">
    <TextBlock Margin="10,10,10,10" FontWeight="Bold">
        Pick a color from below list
   
</TextBlock>
    <ListBox Name="mcListBox" Height="100" Width="100"
             Margin="10,10,0,0" HorizontalAlignment="Left" >
        <ListBoxItem>Orange</ListBoxItem>
        <ListBoxItem>Green</ListBoxItem>
        <ListBoxItem>Blue</ListBoxItem>
        <ListBoxItem>Gray</ListBoxItem>
        <ListBoxItem>LightGray</ListBoxItem>
        <ListBoxItem>Red</ListBoxItem>
    </ListBox>
  
<TextBox Height="23" Name="textBox1" Width="120" Margin="10,10,0,0" HorizontalAlignment="Left"  >
        <TextBox.Text>
            <Binding ElementName="mcListBox" Path="SelectedItem.Content"/>
        </TextBox.Text>
    </TextBox>
    <Canvas Margin="10,10,0,0" Height="200" Width="200" HorizontalAlignment="Left" >
        <Canvas.Background>
            <Binding ElementName="mcListBox" Path="SelectedItem.Content"/>
        </Canvas.Background>
    </Canvas>
</
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 below code, we are setting the SelectedItem.Content property of ListBox to TextBox.Text property.

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

Now 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.

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

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 check boxes. In 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 critics are most welcome. Feel free to post them at the bottom of this article.

Categories

More Articles

© 2020 DotNetHeaven. All rights reserved.