If this is all the sorting you are going to do inside this control, a good option would be to set ListCollectionView.CustomSort to an IComparer instance that performs natural sorting. This will associate the implementation with the type of elements in your ListView , but if this type does not change very often, this is a reasonable limitation. Sorting, on the other hand, will be much faster because it does not need to include reflection.
Assuming you have a comparator like this:
var comparer = new ...
then all you have to do is install it:
var view = (ListCollectionView) CollectionViewSource.GetDefaultView(ListBox.ItemsSource); view.CustomSort = comparer;
It is easy. So, now we only need to find out what comparer looks like ... Here is a very good answer showing how to implement such a comparator:
[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) {
So, given the comparative example above, you should find everything that works with
var view = (ListCollectionView) CollectionViewSource.GetDefaultView(ListBox.ItemsSource); view.CustomSort = new NaturalOrderComparer();
source share