設(shè)計(jì)帶圖標(biāo)和自定義顏色的ListBox

字號(hào):

在一個(gè)點(diǎn)對(duì)點(diǎn)文件傳輸?shù)捻?xiàng)目中,我需要顯示文件傳輸?shù)膶?shí)時(shí)信息:傳輸?shù)奈募斜砗彤?dāng)前傳輸?shù)奈募?,?dāng)時(shí)我想到了用ListBox,但是但我用了ListBox后,我發(fā)現(xiàn)它不能改變控件中文本想的顏色,于是我就想擴(kuò)展一下ListBox控件------ListBoxEx。
    我的目標(biāo)是給空間加上圖標(biāo),還要能時(shí)時(shí)改變控件文本顏色。于是從ListBox派生類
    public class ListBoxEx : ListBox {…}
    為了操作方便我為ListBoxEx的每一項(xiàng)設(shè)計(jì)專門的類ListBoxExItem
    public class ListBoxExItem {…}
    為了保持我這個(gè)控件與WinForm的標(biāo)準(zhǔn)控件的操作借口一致,我又重新設(shè)計(jì)了兩個(gè)集合類:
    public class ListBoxExItemCollection : IList, ICollection, IEnumerator {}
    //這個(gè)類相對(duì)于標(biāo)準(zhǔn)ListBox中的ObjectCollection,這個(gè)類作為ListBoxEx中的Items屬性的類型
    public class SelectedListBoxExItemCollection : : IList, ICollection, IEnumerator{}
    //這個(gè)類相對(duì)于標(biāo)準(zhǔn)ListBox中的SelectedObjectCollection,這個(gè)類作為ListBoxEx中的SelectedItems屬性的類型
    下面看兩個(gè)集合類的實(shí)現(xiàn):
    ListBoxExItemCollection的實(shí)現(xiàn):為了做到對(duì)集合(Items)的操作能夠及時(shí)反映到ListBoxEx的控件中所以,此類只是對(duì)ListBox中Items(ObjectCollection類型)作了一層包裝,就是把ListBox中Items屬性的所有方法的只要是object類型的參數(shù)都轉(zhuǎn)換成ListBoxExItem,比如:
    public void Remove(ListBoxExItem item)
    {
    this._Items.Remove(item); //_Items為ObjectCollection類型
    }
    public void Insert(int index, ListBoxExItem item)
    {
    this._Items.Insert(index, item);
    }
    public int Add(ListBoxExItem item)
    {
    return this._Items.Add(item);
    }
    由上可知,ListBoxExItemCollection中有一個(gè)構(gòu)造函數(shù)來傳遞ListBox中的Items對(duì)象
    private ObjectCollection _Items;
    public ListBoxExItemCollection(ObjectCollection baseItems)
    {
    this._Items = baseItems;
    }
    而SelectedListBoxExItemCollection類的實(shí)現(xiàn)也用同樣的方法,只不過是對(duì)SelectedObjectCollection包裝罷了。
    集合實(shí)現(xiàn)后,再來看ListBoxExItem的實(shí)現(xiàn):