C# 如何在WPF中的listitemcollection中按整数排序?

C# 如何在WPF中的listitemcollection中按整数排序?,c#,wpf,C#,Wpf,我有一个列表框,其排序如下: ListBox.Items.SortDescriptions.Add(new SortDescription("Order", ListSortDirection.Descending)); 但它是按字母排序的,而不是按数字排序的! 怎么做 顺便说一下-属性(aka column)作为varchar存储在数据库中,属性是字符串。但是我想把它转换成一个整数。 我尝试了另一个属性,它是一个整数,我根本无法排序!它抛出了一个例外 如果这是您将在该控件内执行的所有排序,那

我有一个列表框,其排序如下:

ListBox.Items.SortDescriptions.Add(new SortDescription("Order", ListSortDirection.Descending));
但它是按字母排序的,而不是按数字排序的! 怎么做

顺便说一下-属性(aka column)作为varchar存储在数据库中,属性是字符串。但是我想把它转换成一个整数。
我尝试了另一个属性,它是一个整数,我根本无法排序!它抛出了一个例外

如果这是您将在该控件内执行的所有排序,那么一个好的选择是设置一个执行自然排序的实例。这会将实现与
列表视图中的项目类型相耦合,但如果该类型不会经常更改,则这是一个合理的限制。另一方面,排序会快得多,因为它不需要涉及反射

假设您有这样一个比较器:

var comparer = new ...
[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 = comparer;
那很容易。所以现在我们只需要找出比较器的样子。。。下面是一个演示如何实现这种比较器的示例:

var comparer = new ...
[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();

列表中的项目是什么?您是手动填充列表还是通过绑定到数据源填充列表?