C# WPF ListBox Tutorial and Example

C# WPF ListBox Tutorial and Example

C# WPF ListBox Tutorial and Example

This is a C# Windows Presentation Foundation ListBox Tutorial and Example. Normally a ListBox is a component that allows us render lists of items.

ListBoxes are usually single column and are meant to be used for simple items. For more complex lists you can use a ListView.

Showing ListBox in XAML

ListBox like other components have to be represented in XAML first before being used from the C# code. XAML is an extension to XML.

Normally you add components like ListBox inside a window. Then in fact you wrap the component under some form of layout.

Here's an example of adding a listbox to a window and wrapping the listbox inside a grid.

<Window x:Class="MrListBox.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="WPF ListBo" Height="387.285" Width="525">
    <Grid>
        <ListBox x:Name="myListBox" HorizontalAlignment="Left" Height="258" Margin="137,51,0,0" VerticalAlignment="Top" Width="281" SelectionChanged="myListBox_SelectionChanged"/>
    </Grid>
</Window>

Clearly you can see that we have specified the following components:

  1. x:Name - Name of the ListBox. This is used to identify or reference it from the code.
  2. HorizontalAlignment - aligns the listbox horizontally to the specified value.
  3. Height - Height of the listbox
  4. Margin - Margin all around the ListBox
  5. VerticalAlignment - aligns the listbox vertically to the specified value.
  6. Width - Width of the listbox.
  7. SelectionChanged - This is the SelectionChanged event. We assign it as a value our event handler. That event handler will have to be created in the C# code.

How to Bind Data to WPF ListBox

Well ListBox class has the ItemsSource property which makes it easy for us to bind it simple collections.

For example suppose we have an array nameed nebulas, we can simply bind data in the following way:

            myListBox.ItemsSource = nebulas;

How to Handle SelectionChanged events in WPF ListBox

ListBox has several events which we can listen to. The most commonly used is the SelectionChanged event. This gets raised whenever a user selects a different item in our ListBox. You can listen to this event and show a messagebox or open a new form.

But first it has to be registered. For that you go to your XAML and the SelectionChanged property to your ListBox, assigning it an event handler. For example say we have a listbox specified this way:

        <ListBox x:Name="myListBox"  SelectionChanged="myListBox_SelectionChanged"/>

Then in your C# code you can create the event handler this way:

        private void myListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            //... do something here.
        }

How to Get Selected Item in WPF ListBox

Most of the time you want to get the selected item to show or use in some way. That's quite easy. However you have to first listen to SelectionChanged events as we've discussed before. Then in the event handler get that selected item using the SelectedItem property.

myListBox.SelectedItem

Let's say you want to show it in a messagebox:

        private void myListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            MessageBox.Show(myListBox.SelectedItem.ToString(), "Nebulas", MessageBoxButton.OK,
                MessageBoxImage.Information);
        }

Video Tutorial

Here's a video tutorial:

C# WPF ListBox and Array Example

In this project we want to see how we can bind a simple array of data to a ListBox. This is a WPF tutorial so we start by writing some xaml.

Here's the demo.

(a). Create WPF Project

Start by creating a wpf project in your Visual Studio.

(b). MainWindow.xaml

This is the MainWindow.xaml file. Here we add a Window as our root XAML element. This will represent a window for our application.

The window will have a title and dimensions like width and height specified.

Inside it we have a Grid which will arrange our wpf components. The first of them is a Label. That Label will show our header title. We provide that text in the Content attribute.

Then below the header label we will have a ListBox. That ListBox will have several properties specified.

<Window x:Class="MrListBox.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="C# WPF : ListBox - Bind From Array" Height="387.285" Width="525">
    <Grid>
        <Label Content="Nebulars" HorizontalAlignment="Left" Margin="208,10,0,0" VerticalAlignment="Top" FontWeight="Bold" FontSize="20" FontFamily="Shonar Bangla" Width="123"/>
        <ListBox x:Name="myListBox" HorizontalAlignment="Left" Height="258" Margin="137,51,0,0" VerticalAlignment="Top" Width="281" SelectionChanged="myListBox_SelectionChanged"/>

    </Grid>
</Window>

MainWindow.xaml.cs

First we will move to the MainWindow.xaml.cs code and add two using directives:

using System.Windows;
using System.Windows.Controls;

Then in our class as an instance field we will have a string array. This will act as our data source.

        private readonly string[] nebulas = {"Horse Head","Orion","Boomerang","Bernad 68","Witch Head","Black Widow","Pelican","Helix","Snake","Elephant's Trunk","Flame","Cone","Own","Ring","Ant Nebular","Butterfly"};

Below it will bind our array to our listbox:

            myListBox.ItemsSource = nebulas;

In our event handler we will be showing the selected item in a messagebox.

Here's the full MainWindow.xaml.cs code.

using System.Windows;
using System.Windows.Controls;

namespace MrListBox
{
    public partial class MainWindow : Window
    {
        private readonly string[] nebulas = {"Horse Head","Orion","Boomerang","Bernad 68","Witch Head","Black Widow","Pelican","Helix","Snake","Elephant's Trunk","Flame","Cone","Own","Ring","Ant Nebular","Butterfly"};
        private void bindListBox()
        {
            myListBox.ItemsSource = nebulas;
        }
        private void myListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            MessageBox.Show(myListBox.SelectedItem.ToString(), "Nebulas", MessageBoxButton.OK,
                MessageBoxImage.Information);
        }
        public MainWindow()
        {
            InitializeComponent();
            bindListBox();
        }
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *