WPF: Selecting An Item In Listbox

This entry is part 21 of 54 in the series Learn WPF

A list box is like a drop down list except that more than one item in the list box is visible.

If you look at the formation of a list box in the XAML, it is actually formed by a nested list of ListBoxItem.

<Window x:Class="ListBox1.MainWindow"
        Title="MainWindow" Height="350" Width="525">
    <StackPanel Margin="50,50,50,50">
        <TextBox Name="tb" Width="140" Height="30"></TextBox>
        <ListBox Name="lb" Width="100" Height="55" SelectionChanged="DisplayOutput" SelectionMode="Single">
            <ListBoxItem>Item 1</ListBoxItem>
            <ListBoxItem>Item 2</ListBoxItem>
            <ListBoxItem>Item 3</ListBoxItem>
            <ListBoxItem>Item 4</ListBoxItem>
            <ListBoxItem>Item 5</ListBoxItem>
            <ListBoxItem>Item 6</ListBoxItem>

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

namespace ListBox1
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
        public MainWindow()

        void DisplayOutput(object sender, SelectionChangedEventArgs args)
            ListBoxItem lbi = ((sender as ListBox).SelectedItem as ListBoxItem);
            tb.Text = "   You selected " + lbi.Content.ToString() + ".";

As ListBox contains nested ListItemBox, we need to pay attention to line 30.

The object sender that is sent into the DisplayOutput method needs to be first converted to a ListBox.  We need to make another casting to ListBoxItem in order to print out the selected item in the list.

ListBoxItem lbi = ((sender as ListBox).SelectedItem as ListBoxItem);

Below here the output from running the code above:


Series Navigation<< WPF: Radio button
WPF: Data binding with slider >>

Leave a comment

Leave a Reply