2012-05-14 40 views
0

我有有着幾分像這樣的列表框:如何按照WPF中listitemcollection中的整數進行排序?

ListBox.Items.SortDescriptions.Add(new SortDescription("Order", ListSortDirection.Descending)); 

但按字母順序排序,而不是數值! 如何做到這一點?

順便說一句 - 屬性(又名列)作爲varchar存儲在數據庫中,屬性是一個字符串。但不知何故,我想將其轉換爲整數。 我嘗試了另一個屬性,它是一個整數,我根本無法分類!它拋出一個異常!

+0

列表中有哪些項目? –

+0

您是手動填充列表還是通過綁定到數據源? – Jon

+0

綁定到數據源 – marko

回答

2

如果這是您要在該控件內進行的所有排序,那麼最好選擇將ListCollectionView.CustomSort設置爲IComparer自然排序的實例。這會將實現與ListView中的項目類型相耦合,但如果這種類型不會經常更改,這是一個合理的限制。另一方面,排序會更快,因爲它不需要涉及反思。

假設你有這樣的比較器:

var comparer = new ... 

那麼所有你需要做的是安裝它:

var view = (ListCollectionView) 
      CollectionViewSource.GetDefaultView(ListBox.ItemsSource); 
view.CustomSort = comparer; 

這很容易。所以,現在我們只需要找出什麼comparer樣子......這裏是展示如何實現這樣的比較器一個very good answer

[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(); 
工作
相關問題