Sorting the standard ListView control - Rudi Grobler

Sorting the standard ListView control

I've added an example of how to bind to a ListView control in my binding presentation.

While implementing this, it occurred to me that a common scenario would require to be able to sort a column by clicking on the header! While this is a common requirement, ListView doesn't support this by default. There is no event in the ListView class that traps events when the user clicked on the header! Well, this can easily be fixed by using routed events. To add a handler for when the user clicks on the header, just add the following line of code:

ListView1.AddHandler(GridViewColumnHeader.ClickEvent, new RoutedEventHandler(OnHeaderClicked));

Now you should start getting events whenever the user clicks on the header of the ListView. The next step is to sort the list once your received the event. Here is the code snipped:

private void OnHeaderClicked(object sender, RoutedEventArgs e)
{
    GridViewColumnHeader header = e.OriginalSource as GridViewColumnHeader;
    ListView source = e.Source as ListView;
    try
    {
        ICollectionView dataView = CollectionViewSource.GetDefaultView(source.ItemsSource);
        dataView.SortDescriptions.Clear();
        SortDescription description = new SortDescription(header.Content.ToString(), ListSortDirection.Ascending);
        dataView.SortDescriptions.Add(description);
        dataView.Refresh();
    }
    catch (Exception)
    {
    }
}

That wasn't to hard now was it? This code has 1 major flaw thou... It looks at the header.Content.ToString() to determine what property name to sort by!!! What if the header used the more understandable "Phone (Home)" and not the property name "PhoneHome". Well, in my current design only sorting by name and surname will work because these friendly names map directly to the property names! If you need to be able to sort by other headings that do not equal the property names, you sould think about implementing a custom GridViewColumn! There are 2 great resources available to see how to do this:

http://blogs.interknowlogy.com/joelrumerman/archive/2007/04/03/12497.aspx

or download Family.Show by Vertigo from codeplex. Thy implemented a SortListViewColumn and SortListView. Just replace your normal GridViewColumn and ListView with there stuff and you magically have sorting enabled!!!

Published Friday, November 23, 2007 1:18 PM by rudi
Filed under: ,

Comments

# Sorting a standard ListView Control in WPF

You've been kicked (a good thing) - Trackback from DotNetKicks.com

Friday, November 23, 2007 1:34 PM by DotNetKicks.com