设计带图标和自定义颜色的ListBox
http://tech.ddvip.com 2006年08月01日 社区交流
本文详细介绍设计带图标和自定义颜色的ListBox
为了支持图标,添加一个图像列表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以完整的实现,并且支持可视化设计。
责编:豆豆技术应用