It’s quite simple, in WPF, to present data in a grid, thanks to the GridView class. If you want to sort it, however, it gets a little harder… With the DataGridView in Windows Forms, it was “automagic” : when the user clicked a column header, the grid was automatically sorted. To achieve the same behavior in WPF, you need to get your hands dirty… The method recommended by Microsoft is described in this article ; it is based on the Click event of the GridViewColumnHeader class. In my view, this approach has two major drawbacks :
- The sorting must be done in code-behind, something we usually want to avoid if the application is designed according to the MVVM pattern. It also makes the code harder to reuse.
- This method assumes that the text of the column header is also the name of the property to use as the sort criteria, which isn’t always true, far from it… We could use the
DisplayMemberBindingof the column, but it’s not always set (for instance if aCellTemplateis defined instead).
After spending a long time trying to find a flexible and elegant approach, I came up with an interesting solution. It consists of a class with a few attached properties that can be set in XAML.
This class can be used as follows :
<ListView ItemsSource="{Binding Persons}"
IsSynchronizedWithCurrentItem="True"
util:GridViewSort.AutoSort="True">
<ListView.View>
<GridView>
<GridView.Columns>
<GridViewColumn Header="Name"
DisplayMemberBinding="{Binding Name}"
util:GridViewSort.PropertyName="Name"/>
<GridViewColumn Header="First name"
DisplayMemberBinding="{Binding FirstName}"
util:GridViewSort.PropertyName="FirstName"/>
<GridViewColumn Header="Date of birth"
DisplayMemberBinding="{Binding DateOfBirth}"
util:GridViewSort.PropertyName="DateOfBirth"/>
</GridView.Columns>
</GridView>
</ListView.View>
</ListView>
The GridViewSort.AutoSort property enables automatic sorting for the ListView. The GridViewSort.PropertyName property, defined for each column, indicates the property to use as the sort criteria. There is no extra code to write. A click on a column header triggers the sorting on this column ; if the ListView is already sorted on this column, the sort order is reversed.
In case you need to handle the sorting manually, I also added a GridViewSort.Command attached property. When used with the MVVM pattern, this property allows you to bind to a command declared in the ViewModel :
<ListView ItemsSource="{Binding Persons}"
IsSynchronizedWithCurrentItem="True"
util:GridViewSort.Command="{Binding SortCommand}">
...
The sort command takes as parameter the name of the property to use as the sort criteria.
Note : if both the Command and AutoSort properties are set, Command has priority. AutoSort is ignored.
Here is the full code of the GridViewSort class :
using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
namespace Wpf.Util
{
public class GridViewSort
{
#region Attached properties
public static ICommand GetCommand(DependencyObject obj)
{
return (ICommand)obj.GetValue(CommandProperty);
}
public static void SetCommand(DependencyObject obj, ICommand value)
{
obj.SetValue(CommandProperty, value);
}
// Using a DependencyProperty as the backing store for Command. This enables animation, styling, binding, etc...
public static readonly DependencyProperty CommandProperty =
DependencyProperty.RegisterAttached(
"Command",
typeof(ICommand),
typeof(GridViewSort),
new UIPropertyMetadata(
null,
(o, e) =>
{
ItemsControl listView = o as ItemsControl;
if (listView != null)
{
if (!GetAutoSort(listView)) // Don't change click handler if AutoSort enabled
{
if (e.OldValue != null && e.NewValue == null)
{
listView.RemoveHandler(GridViewColumnHeader.ClickEvent, new RoutedEventHandler(ColumnHeader_Click));
}
if (e.OldValue == null && e.NewValue != null)
{
listView.AddHandler(GridViewColumnHeader.ClickEvent, new RoutedEventHandler(ColumnHeader_Click));
}
}
}
}
)
);
public static bool GetAutoSort(DependencyObject obj)
{
return (bool)obj.GetValue(AutoSortProperty);
}
public static void SetAutoSort(DependencyObject obj, bool value)
{
obj.SetValue(AutoSortProperty, value);
}
// Using a DependencyProperty as the backing store for AutoSort. This enables animation, styling, binding, etc...
public static readonly DependencyProperty AutoSortProperty =
DependencyProperty.RegisterAttached(
"AutoSort",
typeof(bool),
typeof(GridViewSort),
new UIPropertyMetadata(
false,
(o, e) =>
{
ListView listView = o as ListView;
if (listView != null)
{
if (GetCommand(listView) == null) // Don't change click handler if a command is set
{
bool oldValue = (bool)e.OldValue;
bool newValue = (bool)e.NewValue;
if (oldValue && !newValue)
{
listView.RemoveHandler(GridViewColumnHeader.ClickEvent, new RoutedEventHandler(ColumnHeader_Click));
}
if (!oldValue && newValue)
{
listView.AddHandler(GridViewColumnHeader.ClickEvent, new RoutedEventHandler(ColumnHeader_Click));
}
}
}
}
)
);
public static string GetPropertyName(DependencyObject obj)
{
return (string)obj.GetValue(PropertyNameProperty);
}
public static void SetPropertyName(DependencyObject obj, string value)
{
obj.SetValue(PropertyNameProperty, value);
}
// Using a DependencyProperty as the backing store for PropertyName. This enables animation, styling, binding, etc...
public static readonly DependencyProperty PropertyNameProperty =
DependencyProperty.RegisterAttached(
"PropertyName",
typeof(string),
typeof(GridViewSort),
new UIPropertyMetadata(null)
);
#endregion
#region Column header click event handler
private static void ColumnHeader_Click(object sender, RoutedEventArgs e)
{
GridViewColumnHeader headerClicked = e.OriginalSource as GridViewColumnHeader;
if (headerClicked != null)
{
string propertyName = GetPropertyName(headerClicked.Column);
if (!string.IsNullOrEmpty(propertyName))
{
ListView listView = GetAncestor<ListView>(headerClicked);
if (listView != null)
{
ICommand command = GetCommand(listView);
if (command != null)
{
if (command.CanExecute(propertyName))
{
command.Execute(propertyName);
}
}
else if (GetAutoSort(listView))
{
ApplySort(listView.Items, propertyName);
}
}
}
}
}
#endregion
#region Helper methods
public static T GetAncestor<T>(DependencyObject reference) where T : DependencyObject
{
DependencyObject parent = VisualTreeHelper.GetParent(reference);
while (!(parent is T))
{
parent = VisualTreeHelper.GetParent(parent);
}
if (parent != null)
return (T)parent;
else
return null;
}
public static void ApplySort(ICollectionView view, string propertyName)
{
ListSortDirection direction = ListSortDirection.Ascending;
if (view.SortDescriptions.Count > 0)
{
SortDescription currentSort = view.SortDescriptions[0];
if (currentSort.PropertyName == propertyName)
{
if (currentSort.Direction == ListSortDirection.Ascending)
direction = ListSortDirection.Descending;
else
direction = ListSortDirection.Ascending;
}
view.SortDescriptions.Clear();
}
if (!string.IsNullOrEmpty(propertyName))
{
view.SortDescriptions.Add(new SortDescription(propertyName, direction));
}
}
#endregion
}
}
Of course, this class could probably be improved… for instance, we could add an arrow glyph on the sorted column (maybe by using an Adorner). Maybe I’ll do that someday… meanwhile, please feel free to use it
Update : A new version that displays the sort glyph in the sorted column is now available in this blog post.





Bon boulot !
J”avais trouvé un exemple il y a quelque temps sur CodeProject mais il me restait le problème du nom de la colonne vis-à-vis du nom de la propriété… J”aime bien aussi le binding avec la commande (MVVM powered :p)
Merci à toi
Very nice! Works like a charm!
A hint to everyone. “AutoSort” is really “EnableFeature”, if you don”t set it, nothing happens. I had originally assumed that AutoSort meant “Sort the table when the data loads”, but this was not the case. Hopefully this saves people 10 minutes.
Hi Matt,
Indeed the name of that property may be somewhat misleading… perhaps “Enable” would have been a better name.
Actually, you don”t have to set
AutoSortto true : another option is to set theCommandproperty, in order to sort the data manually (as opposed to automatically, hence the name “AutoSort”)Hello!
I love your solution, works perfectly in my project!
but i would really want to make it sort it self on load, as Matt is talking about.
I have been trying for a while now, but i cannot find a solution when usin the MVVM pattern.
Do you have an idea/hint/way to do it?
Best Regards
Jakob
Hi Jakob,
You just need to add a SortDescription to the default view for your collection :
var view = CollectionViewSource.GetDefaultView(yourCollection);
var sortDescription = new SortDescription("SomeProperty", ListSortDirection.Ascending);
view.SortDescriptions.Add(sortDescription);
Best Regards,
Thomas
oh of cause!
i should have known that! must be too much summer vacation!
thank you
Hi Thomas,
Thanks for a great solution.
I”ve just got a question.. This default sorting method works fine, sorting order is fine, but glyph is not visible at the beginning, user has to press on some column to make it visible..
Any ideas to get it displayed also at the beginning?
If it makes any difference, my binding happens in constructor.
Hi Alexey,
I”m aware of this issue, I was trying to solve it just 2 days ago… Unfortunately it turned out to be much harder than I expected, and I don”t have a solution yet. If I find a good solution I will post it here
Regards,
Thomas
Here:
public static string GetPropertyName(DependencyObject obj)
{
return (string)obj.GetValue(PropertyNameProperty);
}
you should check for obj != null
null happens when you click the last extra column
Good point… however, I think it would make more sense to check the value of
headerClicked.Columnbefore calling GetPropertyName.Serait ce possible d”Avoir la classe gridviewsort en VB NET
Merci
Je ne code en VB.NET que quand je n”ai vraiment pas le choix… mais il y a des convertisseurs qui doivent pouvoir faire le boulot
En voilà un : http://www.developerfusion.com/tools/convert/csharp-to-vb/
That was INCREDIBLY helpful, thanks.
This sorting seem to be happening on the display string of values in column. Can we do something to really sort based on the value of date of birth?
Hi Niraj, for me the sorting is done on the actual value, not the display string… are you sure you”re are really binding to a date, not a string?
Hey Thomas,
I”ve been looking into the code, but for some reason i can”t get it working.
(Could be cause i”ve only been working with WPF for 2 weeks now.)
The problem lies here:
and here:
I haven”t been able to get the util thing working for me. I figured by looking at your project it has to do with the namespace, so i already changed that to my projects namespace, but that didn”t help. Could you tell me what i”m missing here?
Hi Jeroen,
I think there”s something missing in your comment… if you need to post some code, use the sourcecode tag as described here
Let”s see if this works:
<ListView ItemsSource="{Binding Persons}" IsSynchronizedWithCurrentItem="True" util:GridViewSort.AutoSort="True"> <ListView.View> <GridView> <GridView.Columns> <GridViewColumn Header="Name" DisplayMemberBinding="{Binding Name}" util:GridViewSort.PropertyName="Name"/> <GridViewColumn Header="First name" DisplayMemberBinding="{Binding FirstName}" util:GridViewSort.PropertyName="FirstName"/> <GridViewColumn Header="Date of birth" DisplayMemberBinding="{Binding DateOfBirth}" util:GridViewSort.PropertyName="DateOfBirth"/> </GridView.Columns> </GridView> </ListView.View> </ListView>Are you getting a compile error? Did you map the XAML namespace
utilto the C# namespace where theGridViewSortclass is declared?Hmm ok, nvm, looked some bit deeper into it and now got it working for a few of my columns. Still gotta fix the date notation though.
Thanks for the example.
Ye the problem was mapping to the class. Like i said, new in this so didn”t know that part, but trying some (for me) “weird” things helped.
This is simply great and works perfect when binding to simple properties. Any thoughts on how to achieve similar functionality when binding and using a value converter? Some of my fields are complex types and I want to sort on the converted string values. Am I forced to use a command? I am hoping to avoid since it forces my viewmodel to know about how the view will render the data.
Hi Ian,
This solution is based on ICollectionView.SortDescriptions, and SortDescription only accepts a property name, not a “full” binding with a converter. If you need to sort based on more complex criteria, you can create an extra property in the VM of your data items, implement the converter logic in that property, and sort on that property. That”s what I do and it works fine.
Regards,
Thomas
Just wanted to add my thanks as well! I love it!
Thank you for this. This class is very useful!
it”s works with command? because,it doesn”t binding to my command
sorry, my bad. it works
I actually liked your original idea here more: http://stackoverflow.com/questions/1221533/sort-wpf-listview-with-a-datatemplate-instead-of-displaymemberbinding
So I enhanced the GetPropertyName so that the user can specify the GridViewSort.PropertyName. If they choose not to, it will fallback on automatically trying to get the DisplayMemberBinding Path. Makes for less repetitive looking code, but still lets you handle the special cases.
public static string GetPropertyName(DependencyObject obj) { if( obj == null ) return null; try { string propertyName = (string)obj.GetValue(PropertyNameProperty); if( string.IsNullOrEmpty(propertyName) && obj is GridViewColumn ) { GridViewColumn column = (GridViewColumn)obj; if( column.DisplayMemberBinding != null ) { propertyName = ((Binding)column.DisplayMemberBinding).Path.Path; } } return propertyName; } catch { return null; } }Thomas, thank you! The code works fantastically for what I need it to do.
And alainbryden, thank you, too, because your modification does EXACTLY what I was just about to go figure out how to do. Using DisplayMemberBinding.Path.Path is a special kind of magic.
mazel tov! works perfectly!
Hi, Thomas:
This article is awesome. Can we use the code in this article in commercial software?
Hi Ray, there is no restriction whatsoever on the use of this code, you can use it in any project you want.
how can i get the (util) in xaml? I got erors in it..
Hi Jesson,
You need to map the C# namespace where you declare the class to the “util” XML namespace on the root element, like this:
(you can omit the assembly part if it”s in the same assembly)
got it man.. thanks alot
hello to all the community
Is this ok to email this article to our email list
Sure, you can send a link