WinForm-ListBox控件美化

转载

如果要对ListBox控件进行自定义绘制(美化),那么首先必须将ListBox的DrawMode属性设置为OwnerDrawVariable或OwnerDrawFixed。ListBox有个ItemHeight属性,在DrawMode设置为Normal时,这个属性是不可设置的,并且其值是根据当前字体进行计算获得的。只有当DrawMode设置为OwnerDrawVariable或OwnerDrawFixed时,设置ItemHeight才生效。

属性

说明

Normal

组件的所有元素都由操作系统绘制,并且元素大小都相等。

OwnerDrawFixed

组件的所有元素都是手动绘制的,并且元素大小都相等。

OwnerDrawVariable

组件的所有元素都由手动绘制,元素大小可能不相等。

表01:枚举DrawMode中的成员及其说明
设置完DrawMode属性之后,通过ListBox的DrawItem事件可以绘制自己想要的个性化控件。先看一下自己绘制的ListBox控件的效果图:
WinForm-ListBox控件美化 WinForm-ListBox控件美化 (这是选中“英语”的效果)
从图中可以看出,针对不同的行绘制了不同的背景色,选中项的背景色设置为蓝色,并且还绘制了一个边框。确实比系统绘制的ListBox好看多了。下面我们来看看代码,也就是DrawItem事件处理方法。
代码

   1: private void listBox1_DrawItem(object sender, 
   2: DrawItemEventArgs e) 
   3: { 
   4: int index = e.Index;//获取当前要进行绘制的行的序号,从0开始。 
   5:  
   6: Graphics g = e.Graphics;//获取Graphics对象。 
   7: Rectangle bound = 
   8: e.Bounds;//获取当前要绘制的行的一个矩形范围。 
   9: string text = 
  10: listBox1.Items[index].ToString();//获取当前要绘制的行的显示文本。 
  11: if ((e.State & 
  12: DrawItemState.Selected) == DrawItemState.Selected) 
  13: {//如果当前行为选中行。 
  14:  
  15: //绘制选中时要显示的蓝色边框。 
  16: g.DrawRectangle(Pens.Blue, bound.Left, bound.Top, 
  17: bound.Width - 1, bound.Height - 1); 
  18: Rectangle rect = new 
  19: Rectangle(bound.Left 2, bound.Top 2, 
  20: bound.Width - 4, bound.Height - 4); 
  21:  
  22: //绘制选中时要显示的蓝色背景。 
  23: g.FillRectangle(Brushes.Blue, rect); 
  24: //绘制显示文本。 
  25:  
  26: TextRenderer.DrawText(g, text, this.Font, rect, Color.White, 
  27:  
  28: TextFormatFlags.VerticalCenter | TextFormatFlags.Left); 
  29: } 
  30: else 
  31:  
  32: { //GetBrush为自定义方法,根据当前的行号来选择Brush进行绘制。 
  33: using (Brush brush = 
  34: GetBrush(e.Index)) 
  35: { 
  36: g.FillRectangle(brush, bound);//绘制背景色。 
  37: } 
  38:  
  39: TextRenderer.DrawText(g, text, this.Font, bound, Color.White, 
  40:  
  41: TextFormatFlags.VerticalCenter | TextFormatFlags.Left); 
  42: } 
  43: } 

OwnerDrawVariable
设置DrawMode属性为OwnerDrawVariable后,可以任意改变每一行的ItemHeight和ItemWidth。通过ListBox的MeasureItem事件,可以使每一行具有不同的大小。
WinForm-ListBox控件美化 (奇偶行的行高不同)

 

   1: private void listBox1_MeasureItem(object sender, 
   2: MeasureItemEventArgs e) 
   3: { 
   4: //偶数行的ItemHeight为20 
   5: if (e.Index % 2 == 0) 
   6: e.ItemHeight = 20; 
   7: //奇数行的ItemHeight为40 
   8: else e.ItemHeight = 40; 
   9: } 
  10:  

总结
这里最重要的是DrawItem事件和MeasureItem事件,以及MeasureItemEventArgs事件数据类和DrawItemEventArgs事件数据类。在System.Windows.Forms命名空间中,具有DrawItem事件的控件有ComboBox、ListBox、ListView、MenuItem、StatusBar、TabControl,具有MeasureItem事件的控件有ComboBox、ListBox、MenuItem。所以,这些控件可以采用和ListBox相同的方法进行自定义绘制。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值