為了支持圖標,添加一個圖像列表imagelist
private ImageList imageList;
public ImageList ImageList
{
get { return this.imageList; }
set
{
this.imageList = value;
this.Invalidate();//圖像列表改變後馬上更新控件
}
}
而此控件的核心卻在一個方法OnDrawItem,這個方法每當控件的項需要重繪時就被調用
protected override void OnDrawItem(System.Windows.Forms.DrawItemEventArgs pe)
{
pe.DrawBackground(); //畫背景
pe.DrawFocusRectangle(); //畫邊框
Rectangle bounds = pe.Bounds;
// Check whether the index is valid
if(pe.Index >= 0 && pe.Index < base.Items.Count)
{
ListBoxExItem item = this.Items[pe.Index]; //取得需要繪制項的引用
int iOffset = 0;
// If the image list is present and the image index is set, draw the image
if(this.imageList != null)
{
if (item.ImageIndex > -1 && item.ImageIndex < this.imageList.Images.Count)
{
this.imageList.Draw(pe.Graphics, bounds.Left, bounds.Top, bounds.Height, bounds.Height, item.ImageIndex); //繪制圖標
}
iOffset += bounds.Height;//this.imageList.ImageSize.Width;
}
// Draw item text
pe.Graphics.DrawString(item.Text, pe.Font, new SolidBrush(item.ForeColor),bounds.Left + iOffset, bounds.Top); //根據項的顏色繪制文本
}
base.OnDrawItem(pe);
}
}
到此為止,ListBoxEx以完整的實現,並且支持可視化設計。