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;
// 檢查索引有效性
if (pe.Index >= 0 && pe.Index < base.Items.Count)
{
ListBoxExItem item = this.Items[pe.Index]; // 取得需繪製項目參考
int iOffset = 0;
// 若有 ImageList 且設定 ImageIndex,繪製圖示
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;
}
// 繪製項目文字,依項目顏色
pe.Graphics.DrawString(item.Text, pe.Font,
new SolidBrush(item.ForeColor), bounds.Left + iOffset, bounds.Top);
}
base.OnDrawItem(pe);
}
至此 ListBoxEx 完整實現,並支援視覺化設計。