在一個點對點文件傳輸的項目中
我的目標是給空間加上圖標
public class ListBoxEx : ListBox {…}
為了操作方便我為ListBoxEx的每一項設計專門的類ListBoxExItem
public class ListBoxExItem {…}
為了保持我這個控件與WinForm的標准控件的操作借口一致
public class ListBoxExItemCollection : IList
//這個類相對於標准ListBox中的ObjectCollection
public class SelectedListBoxExItemCollection : : IList
//這個類相對於標准ListBox中的SelectedObjectCollection
下面看兩個集合類的實現
ListBoxExItemCollection的實現
public void Remove(ListBoxExItem item)
{
this
}
public void Insert(int index
{
this
}
public int Add(ListBoxExItem item)
{
return this
}
由上可知
private ObjectCollection _Items;
public ListBoxExItemCollection(ObjectCollection baseItems)
{
this
}
而SelectedListBoxExItemCollection類的實現也用同樣的方法
集合實現後
為了使它支持圖標和多種顏色添加如下成員
private int _ImageIndex;
public int ImageIndex
{
get { return this
set { this
}
private Color _ForeColor;
public Color ForeColor
{
get{ return this
set
{
this
this
}
}
當然還有
private string _Text;
public string Text
{
get { return this
set { this
}
為了控件能正確顯示此項的文本
public override string ToString()
{
return this
}
再看ListBoxEx的實現:
為了使控件能夠自我繪制
為了覆蓋基類的Items等相關屬性添加
private ListBoxExItemCollection _Items; //在構造函數中創建
同時還需要重寫屬性Items
new public ListBoxExItemCollection Items
{
get
{
return this
}
}
new public ListBoxExItem SelectedItem //強制轉換為ListBoxExItem
{
get{ return base
set{ base
}
new public SelectedListBoxExItemCollection SelectedItems //重新包裝SelectedItems
{
get
{
return new SelectedListBoxExItemCollection(base
}
}
為了支持圖標
private ImageList imageList;
public ImageList ImageList
{
get { return this
set
{
this
this
}
}
而此控件的核心卻在一個方法OnDrawItem
protected override void OnDrawItem(System
{
pe
pe
Rectangle bounds = pe
// Check whether the index is valid
if(pe
{
ListBoxExItem item = this
int iOffset =
// If the image list is present and the image index is set
if(this
{
if (item
{
this
}
iOffset += bounds
}
// Draw item text
pe
}
base
}
}
到此為止
From:http://tw.wingwit.com/Article/program/net/201311/11713.html