If this is all the sorting you are going to be doing inside that control, a good option would be to set ListCollectionView.CustomSort
to an IComparer
instance that does natural sorting. This will couple the implementation to the type of the items in your ListView
, but if that type is not going to change very often this is a reasonable limitation. On the other hand, the sort will be much faster because it won't need to involve reflection.
Assuming you have such a comparer:
var comparer = new ...
then all you need to do is install it:
var view = (ListCollectionView)
CollectionViewSource.GetDefaultView(ListBox.ItemsSource);
view.CustomSort = comparer;
That's easy. So now we only have to find out what comparer
looks like... Here's a very good answer showing how to implement such a comparer:
[SuppressUnmanagedCodeSecurity]
internal static class SafeNativeMethods
{
[DllImport("shlwapi.dll", CharSet = CharSet.Unicode)]
public static extern int StrCmpLogicalW(string psz1, string psz2);
}
public sealed class NaturalOrderComparer : IComparer
{
public int Compare(object a, object b)
{
// replace DataItem with the actual class of the items in the ListView
var lhs = (DataItem)a;
var rhs = (DataItem)b;
return SafeNativeMethods.StrCmpLogicalW(lhs.Order, rhs.Order);
}
}
So, given the comparer above you should find everything working with
var view = (ListCollectionView)
CollectionViewSource.GetDefaultView(ListBox.ItemsSource);
view.CustomSort = new NaturalOrderComparer();