WPF custom sort
Using IComparer for fast sorting on listbox
ListCollectionView 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;
}
}






