改变ListBox中Items的颜色,并且为ListBox中的项目添加图片。

改变ListBoxItems的颜色,并且为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的高度

                }

 
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值