C# XAML List Boxes


The book Illustrated WPF discusses list box controls. A ListBox is a collection of items displayed to the user, from which he or she can select one or more items. As with all ItemsControls, the items in the ListBox can be of any type derived from the UIElement class, including Images and Buttons. By default, a ListBox sets its width to the width of its widest item.

There are two forms in which you can place items into a ListBox’s Items collection—either by explicitly wrapping each item in a ListBoxItem element or by just placing them in the collection and letting the system implicitly wrap them. Here is what it looks like and the markup and code is also listed.

ListBoxOne

<Window x:Class="ListBoxOne.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:ListBox"
        mc:Ignorable="d"
        Title="List Box One" Height="150" Width="300">
    <StackPanel>
        <ListBox Name="lstbxCats" HorizontalAlignment="Left" Width="100">
            <ListBoxItem>Johnny</ListBoxItem>
            <ListBoxItem>Billy</ListBoxItem>
            <ListBoxItem>Sammy</ListBoxItem>
        </ListBox>
        <Button Click="Button_Click" HorizontalAlignment="Left" Width="100" Padding="10,3" Margin="0,5">Enter</Button>
    </StackPanel>
</Window>

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace ListBoxOne
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            // display the user's selection in the message box
            object obj = lstbxCats.SelectedItem;
            // use the conditional operator which is like the if statement
            // 
            string selected = (obj == null)
                ? "No item selected."
                : (string)((ListBoxItem)obj).Content;
            MessageBox.Show(selected, "Selected Item");
        }
    }
}

C# Language Conditional Operator

The condition must evaluate to true or false. If condition is true, first_expression is evaluated and becomes the result. If condition is false, second_expression is evaluated and becomes the result. Only one of the two expressions is evaluated. Either the type of first_expression and second_expression must be the same, or an implicit conversion must exist from one type to the other. You can express calculations that might otherwise require an if-else construction more concisely by using the conditional operator. The conditional operator cannot be overloaded.

condition ? first_expression : second_expression;

You can place items in the ListBox’s Items collection, even without explicitly creating ListBoxItems for them, as shown in the following markup. Rather than creating explicit ListBoxItems, it inserts two TextBlocks and a Button.

Selection

Whenever the selected item in the ListBox changes, the ListBox’s SelectionChanged event is raised. If you create an event handler in the code-behind, you can assign the name of the event handler to the event, and when the event is raised, the event handler is called. Here is an example of a ListBox with three items. When the item selected changes, a dialog box shows the new selection. Here is an example of a project called ListBoxSimple.

<Window x:Class="ListBoxSimple.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:ListBoxSimple"
        mc:Ignorable="d"
        Title="List Box Simple" Height="150" Width="250">
    <StackPanel>
        <ListBox Name="lstbxCats" HorizontalAlignment="Left" Width="100" SelectionChanged="lstbxCats_SelectionChanged">
            <ListBoxItem>Johnny</ListBoxItem>
            <ListBoxItem>Billy</ListBoxItem>
            <ListBoxItem>Sammy</ListBoxItem>
        </ListBox>
    </StackPanel>
</Window>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace ListBoxSimple
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
        private void lstbxCats_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            ListBox lb = sender as ListBox;
            ListBoxItem lbi = lb.SelectedItem as ListBoxItem;
            MessageBox.Show(lbi.Content.ToString(), "Person Selected");
        }
    }
}

Multiple Selections

By default, only a single item in a ListBox can be selected at any time. But there are several options allowing you to enable selection of multiple items from the ListBox. You set the selection mode with the SelectionMode property. The following are the possible values:

Single: The user can select only a single item from the list. This is the default.

Extended: The user can select multiple items from the list, but must hold down a special key to select items after the first one. − To select additional items after the first, the user must hold down the Ctrl key while selecting items. − To select a range of items, the user can select the first (or last) item and then, while holding down the Shift key, select the last (first) item. This selects all the items in between as well as the first and last items.

Multiple: The user can select multiple items from the list by just clicking them, without having to press any special keys to allow the multiple selection.

private void button_Click(object sender, RoutedEventArgs e)
{
    foreach (ListBoxItem item in lstbxCats.Items)
    {
        //Check to see whether it’s selected.
        if (item.IsSelected)
            // display a message box 
            MessageBox.Show((string)item.Content, "Is Selected");
    }
}

The only difference in the XAML is the SelectionMode property being set as shown below.

<ListBox Name="lstbxCats" SelectionMode="Multiple" HorizontalAlignment="Left" Width="100" >...

Leave a comment

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