2015-11-11 19 views
0

我知道你可以設置一個ListBox來自動排序。有沒有辦法「抓住」排序,以便當ListBox交換兩個項目的位置,以便我可以在另一個列表框上做同樣的重新排序?我想按值排序一個列表框,但將這些值保留在與另一個ListBox相比相同的相對索引位置處。對列表框相對於另一個排序

我可以編寫一個例程來對列表進行冒泡排序,以便我可以自己進行更改,但是我想知道是否有更多的自動化,因爲我可能必須在程序的幾個不同位置執行此操作。

回答

0

不幸的是,Sorted屬性沒有使用IComparable接口實現只是根據項目的ToString的結果進行排序。但不是設置Sorted屬性,您可以使用排序數據源(例如List<>)。

ListBox中的項目創建一個包裝類,並在其上實現IComparable<T>接口。用這些ListBoxItem實例填充List<>,然後在列表上調用Sort方法。因此,您將能夠發送呼叫CompareTo

public partial class Form1 : Form 
{ 
    private class ListBoxItem<T> : IComparable<ListBoxItem<T>> 
     where T : IComparable<T> 
    { 
     private T item; 

     internal ListBoxItem(T item) 
     { 
      this.item = item; 
     } 

     // this makes possible to cast a string to a ListBoxItem<string>, for example 
     public static implicit operator ListBoxItem<T>(T item) 
     { 
      return new ListBoxItem<T>(item); 
     } 

     public override string ToString() 
     { 
      return item.ToString(); 
     } 

     public int CompareTo(ListBoxItem<T> other) 
     {     
      return item.CompareTo(other.item); // here you can catch the comparison 
     } 
    } 

    public Form1() 
    { 
     InitializeComponent(); 
     var items = new List<ListBoxItem<string>> { "Banana", "Apple"}; 
     items.Sort(); 
     listBox1.DataSource = items; 
    } 
+0

謝謝你的幫助。 – Popinjay

相關問題