How to Display Row Numbers in WPF ListView Control with Static Content

by Zoran Horvat

Applications that display data using ListView controls often need to display ordinal position next to each item. Without such field users often have problem navigating and understanding data presented.

One obvious method to provide ordinal position is to enrich underlying type or its ViewModel with a property, something like:

public int Ordinal { get; set; }

Though simple, this method still becomes an obstacle in several typical scenarios:

  • Object is displayed in more than one list at the same time and is associated with more than one ordinal position,
  • We do not have access to source code of the type in which property should be implemented neither the ViewModel is used, or
  • We do not have access to source code which provides data context or items binding and consequently cannot set Ordinal property values in all underlying objects.

To resolve these issues, we are presenting solution which assigns ordinal positions to objects after the fact, i.e. after list view items has been created. In this solution we are providing a value converter which is then bound to ListViewItem instance bound to the underlying object. With this idea on mind, we do not have to modify or access in any way the underlying object. Counting is implemented on the list items level rather than on the level of objects that consist the list being displayed.

Solution relies on a value converter type which converts ListViewItem objects into their respective ordinal positions within parent ListView object. Below is the source code of the OrdinalConverter class.

public class OrdinalConverter: IValueConverter
{
    public object Convert(object value, System.Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {

        ListViewItem lvi = value as ListViewItem;
        int ordinal = 0;

        if (lvi != null)
        {
            ListView lv = ItemsControl.ItemsControlFromItemContainer(lvi) as ListView;
            ordinal = lv.ItemContainerGenerator.IndexFromContainer(lvi) + 1;
        }

        return ordinal;

    }

    public object ConvertBack(object value, System.Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        // This converter does not provide conversion back from ordinal position to list view item
        throw new System.InvalidOperationException();
    }
}

This class provides implementation of the Convert method which expects ListViewItem instance. Then it accesses item's parent ListView object in order to determine ordinal position of the item at hand.

This fairly simple idea is then materialized in XAML by binding each item's data template with ListViewItem instance which is its parent in the visual tree.

<ListView.Resources>
    <local:OrdinalConverter x:Key="OrdinalConverter" />
    <DataTemplate x:Key="OrdinalColumnDataTemplate">
        <TextBlock Text="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=ListViewItem},
            Converter={StaticResource ResourceKey=OrdinalConverter}}" HorizontalAlignment="Right" />
    </DataTemplate>
</ListView.Resources>

Note that XAML code above defines data template for the row number cell so that number is displayed as TextBlock. Now this text block element binds to its ancestor of type ListViewItem. In addition, it points to OrdinalConverter instance as value converter to apply. With all these settings in place, OrdinalConverter's Convert method will be called for every particular item added to the list view, and then it would produce back that item's position (as one-based number).

Full XAML code of the window is as follows.

<Window x:Class="OrdinalDemo.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:OrdinalDemo"
        Title="Ordinal Demo" SizeToContent="WidthAndHeight">
    <ListView>
        <ListView.Resources>
            <Style TargetType="ListViewItem">
                <Setter Property="HorizontalContentAlignment" Value="Stretch" />
            </Style>
            <local:OrdinalConverter x:Key="OrdinalConverter" />
            <DataTemplate x:Key="OrdinalColumnDataTemplate">
                <TextBlock Text="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=ListViewItem},
                    Converter={StaticResource ResourceKey=OrdinalConverter}}" HorizontalAlignment="Right" />
            </DataTemplate>
        </ListView.Resources>
        <ListView.View>
            <GridView>
                <GridViewColumn Header="#" CellTemplate="{StaticResource ResourceKey=OrdinalColumnDataTemplate}" Width="30" />
                <GridViewColumn Header="Value" Width="200" />
            </GridView>
        </ListView.View>
        <ListView.Items>
            <ListViewItem>Something</ListViewItem>
            <ListViewItem>Again</ListViewItem>
            <ListViewItem>And</ListViewItem>
            <ListViewItem>Again</ListViewItem>
        </ListView.Items>
    </ListView>
</Window>

Result of running the code looks like this:

List view control with row numbers

Note that all items in the list have their corresponding row numbers assigned. Especially note that this feature has been applied to objects of type String, which we didn't have to modify or wrap within new type in order to display row numbers.

When is This Applicable

This method can be applied only when items source is static. This includes:

  • Binding to an array or similar structure which is not changed after initialization,
  • Binding to DataTable populated statically from database,
  • Binding to list or similar structure to which new items are only added at the end, or items are deleted from the end, etc.

If items exchange places (Move Up/Down feature), items are added in the middle of the list or existing items are deleted from the middle of the list, then corresponding item indices will not be updated.

In such complex cases, ViewModel or whatever object is bound to the ListView should expose property that indicates ordinal position of the item within a linear structure.


If you wish to learn more, please watch my latest video courses

About

Zoran Horvat

Zoran Horvat is the Principal Consultant at Coding Helmet, speaker and author of 100+ articles, and independent trainer on .NET technology stack. He can often be found speaking at conferences and user groups, promoting object-oriented and functional development style and clean coding practices and techniques that improve longevity of complex business applications.

  1. Pluralsight
  2. Udemy
  3. Twitter
  4. YouTube
  5. LinkedIn
  6. GitHub