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:
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:
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.
This method can be applied only when items source is static. This includes:
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
In this course, you will learn the basic principles of object-oriented programming, and then learn how to apply those principles to construct an operational and correct code using the C# programming language and .NET.
As the course progresses, you will learn such programming concepts as objects, method resolution, polymorphism, object composition, class inheritance, object substitution, etc., but also the basic principles of object-oriented design and even project management, such as abstraction, dependency injection, open-closed principle, tell don't ask principle, the principles of agile software development and many more.
More...
In this course, you will learn how design patterns can be applied to make code better: flexible, short, readable.
You will learn how to decide when and which pattern to apply by formally analyzing the need to flex around specific axis.
More...
This course begins with examination of a realistic application, which is poorly factored and doesn't incorporate design patterns. It is nearly impossible to maintain and develop this application further, due to its poor structure and design.
As demonstration after demonstration will unfold, we will refactor this entire application, fitting many design patterns into place almost without effort. By the end of the course, you will know how code refactoring and design patterns can operate together, and help each other create great design.
More...
In four and a half hours of this course, you will learn how to control design of classes, design of complex algorithms, and how to recognize and implement data structures.
After completing this course, you will know how to develop a large and complex domain model, which you will be able to maintain and extend further. And, not to forget, the model you develop in this way will be correct and free of bugs.
More...
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.