BlackWaspTM

This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

Windows Presentation Foundation
.NET 4.0+

WPF Selection Controls - Separator

The seventy-first part of the Windows Presentation Foundation Fundamentals tutorial continues to look at the use of WPF selection controls. This article describes the Separator, which can be used with ListBox and other items controls.

Separator

In the previous article in the WPF tutorial we looked at the ListBox control. This is one of several controls, based upon the ItemsControl class, that display a list of items from which the user may select.

In the earlier article we looked at a basic list of selectable items. In some cases the items in a ListBox may be logically grouped. In such situations, it can be useful to include one or more Separators in the list. Separators are rendered as part of the list but are not selectable in the same way as the actual items. They provide a visual distinction between sets of related options.

To demonstrate, create a new WPF application in Visual Studio, naming the solution, "SeparatorDemo". Once ready, replace the XAML in the main window with the following code:

<Window x:Class="SeparatorDemo.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Separator Demo"
        Height="200"
        Width="200">
    <Grid>
        <ListBox>
            <ListBoxItem>Sports Car</ListBoxItem>
            <ListBoxItem>Compact Car</ListBoxItem>
            <ListBoxItem>Family Car</ListBoxItem>
            <ListBoxItem>Off-Road Car</ListBoxItem>
            <ListBoxItem>Supersports Bike</ListBoxItem>
            <ListBoxItem>Sports Tourer</ListBoxItem>
            <ListBoxItem>Cruiser</ListBoxItem>
        </ListBox>
    </Grid>
</Window>

The above XAML creates a window containing a ListBox. The list contains seven items. The first four are types of car and the remaining three are styles of motorcycle. However, the list provides no grouping.

WPF Separator demo window

Adding a Separator

Separators can be added to a ListBox using a Separator tag in the XAML. No attributes are required; the XAML is simply inserted wherever a logical separation is required. For example, to group the cars and motorcycles, you could modify the XAML for the ListBox as follows:

<ListBox>
    <ListBoxItem>Sports Car</ListBoxItem>
    <ListBoxItem>Compact Car</ListBoxItem>
    <ListBoxItem>Family Car</ListBoxItem>
    <ListBoxItem>Off-Road Car</ListBoxItem>
    <Separator/>
    <ListBoxItem>Supersports Bike</ListBoxItem>
    <ListBoxItem>Sports Tourer</ListBoxItem>
    <ListBoxItem>Cruiser</ListBoxItem>
</ListBox>

The resultant window appears as follows:

WPF Separator demo window with separator

Try running the program to see the results. Note that it is not possible to select the Separator.

16 June 2014