改变ListBox中Items的颜色,并且为ListBox中的项目添加图片。
这个很简单,只需要下面几个步骤:
1. DrawMode属性设置为自己画
// ListBox1is ListBox control
this.ListBox1.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawVariable;
2. 添加这两个事件:
//tell windows we are interested in drawing items in ListBox on our own
this.lstColor.DrawItem += new DrawItemEventHandler(this.DrawItemHandler);
//tell windows we are interested in providing item size
this.lstColor.MeasureItem +=
new System.Windows.Forms.MeasureItemEventHandler(this.MeasureItemHandler);
3. 为这两个事件添加事件处理函数:
private void listBox1_DrawItem(object sender, System.Windows.Forms.DrawItemEventArgs e)
{
e.DrawBackground(); // 画Item的背景色
e.DrawFocusRectangle(); // 画Item的选中框
// 在合适的位置画图片
e.Graphics.DrawImage(this.imageList1.Images[e.Index],0, e.Index*imageList1.Images[e.Index].Height ,imageList1.Images[e.Index].Width,imageList1.Images[e.Index].Height);
// 字体要在图片之后显示出来,X坐标需要向右移动
Rectangle tmp = new Rectangle(e.Bounds.X + imageList1.Images[e.Index].Width ,e.Bounds.Y,e.Bounds.Width,e.Bounds.Height);
// 画Text的内容 e.Graphics.DrawString(this.listBox1.Items[e.Index].ToString(),
new Font(FontFamily.GenericSansSerif,
14, FontStyle.Bold),
new SolidBrush(Color.Red),
tmp);
}
private void listBox1_MeasureItem(object sender, System.Windows.Forms.MeasureItemEventArgs e)
{
e.ItemHeight = 25; // 每个Item的高度
}