これがそのコントロール内で実行するすべての並べ替えである場合、適切なオプションは、自然な並べ替えListCollectionView.CustomSort
を行うIComparer
インスタンスに設定することです。これにより、実装が 内のアイテムのタイプに結合されますListView
が、そのタイプが頻繁に変更されない場合、これは妥当な制限です。一方、リフレクションを必要としないため、並べ替えははるかに高速になります。
あなたがそのような比較子を持っていると仮定します:
var comparer = new ...
あとはインストールするだけです:
var view = (ListCollectionView)
CollectionViewSource.GetDefaultView(ListBox.ItemsSource);
view.CustomSort = comparer;
簡単だ。だから今、私たちはどのよう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);
}
}
したがって、上記の比較を考えると、すべてが動作することがわかるはずです
var view = (ListCollectionView)
CollectionViewSource.GetDefaultView(ListBox.ItemsSource);
view.CustomSort = new NaturalOrderComparer();