http://www.codinghelmet.com/  

Wear a helmet. Even when coding.

howto > rownum

How to Display Row Numbers in WPF ListView Control with Static Content
by Zoran Horvat @zoranh75

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.

See also:

Published: Mar 10, 2012; Modified: Mar 15, 2012

ZORAN HORVAT

Zoran is software architect dedicated to clean design and CTO in a growing software company. Since 2014 Zoran is an author at Pluralsight where he is preparing a series of courses on object-oriented and functional design, design patterns, writing unit and integration tests and applying methods to improve code design and long-term maintainability.

Follow him on Twitter @zoranh75 to receive updates and links to new articles.

Watch Zoran's video courses at pluralsight.com (requires registration):

Making Your C# Code More Object-Oriented

This course will help leverage your conceptual understanding to produce proper object-oriented code, where objects will completely replace procedural code for the sake of flexibility and maintainability. More...

Advanced Defensive Programming Techniques

This course will lead you step by step through the process of developing defensive design practices, which can substitute common defensive coding, for the better of software design and implementation. More...

Tactical Design Patterns in .NET: Creating Objects

This course sheds light on issues that arise when implementing creational design patterns and then provides practical solutions that will make our code easier to write and more stable when running. More...

Tactical Design Patterns in .NET: Managing Responsibilities

Applying a design pattern to a real-world problem is not as straight-forward as literature implicitly tells us. It is a more engaged process. This course gives an insight to tactical decisions we need to make when applying design patterns that have to do with separating and implementing class responsibilities. More...

Tactical Design Patterns in .NET: Control Flow

Improve your skills in writing simpler and safer code by applying coding practices and design patterns that are affecting control flow. More...

Writing Highly Maintainable Unit Tests

This course will teach you how to develop maintainable and sustainable tests as your production code grows and develops. More...

Improving Testability Through Design

This course tackles the issues of designing a complex application so that it can be covered with high quality tests. More...

Share this article

webmasters