Site statistics
Members : 19Content : 104
Content View Hits : 18421
Who's Online
We have 308 guests online| WPF custom sort |
|
|
|
| Articles - Windows presentation foundation |
| Written by Dot4Pro |
| Saturday, 14 November 2009 12:10 |
Using IComparer for fast sorting on listboxListCollectionView allows to sort listbox in wpf to sort. You bind the listbox to the instance of ListCollectionView.
View.SortDescriptions.Add(new SortDescription(){ PropertyName = columnName,ListSortDirection.Descending}); The above technique uses reflection to sort the ListCollectionView so if you have a large data collection , this can be very slow. For faster sorting you can use CustomSort.
var sortComparer = new UserComparer () View.CustomSort = sortComparer;
Classes
public abstract class SortComparer : IComparer { public string SortColumn; public ListSortDirection Direction; public abstract int Compare(object x, object y); } public class UserComparer : SortComparer { public override int Compare(object x, object y) { var tx = (User)x; var ty = (User)y; int ret = 0; switch (SortColumn) { case "UserName": { ret = Direction == ListSortDirection.Ascending ? tx.UserName.CompareTo(ty.UserName) : ty.UserName.CompareTo(tx.UserName); break; } } return ret; } } |


