[C#.net]ListBox对Item进行重绘,设置背景色和前景色

别的不多说了,上代码,直接看

首先设置这行,或者属性窗口设置,这样才可以启动手动绘制,参数有三个

Normal: 自动绘制

OwnerDrawFixed:手动绘制,但间距相同

OwnerDrawVariable:手动绘制,间距不同

listBox1.DrawMode= DrawMode.OwnerDrawFixed

然后在DrawItem事件中写绘制代码

            e.Graphics.FillRectangle(new SolidBrush(color), e.Bounds);//绘制背景
            e.Graphics.DrawString(listBox1.Items[e.Index].ToString(), e.Font, new SolidBrush(e.ForeColor), e.Bounds);//绘制文字
            e.DrawFocusRectangle();//绘制聚焦框

 其中绘制聚焦框没啥效果,貌似需要是ComboBox仅在DropDownStyle=DropDownList时有效

如果设置为了OwnerDrawVariable,则还需要设置MeasureItem事件,用于返回每行的高度(e.ItemWidth = 260)。

如果是绘制虚线,则pen需要设置DashStyle或者DashPattern(优先级高)。

 1         private void lstLog_DrawItem(object sender, DrawItemEventArgs e)
 2         {
 3             if (e.Index >= 0)
 4             {
 5                 e.DrawBackground();
 6                 Brush myBrush = Brushes.Black; //前景色
 7                 Color bgColor = Color.White;   //背景色
 8                 if(lstLog.Items[e.Index].ToString().Contains("成功"))
 9                 {
10                     bgColor = Color.RoyalBlue;
11                 }
12                 if (lstLog.Items[e.Index].ToString().Contains("失败"))
13                 {
14                     bgColor = Color.Magenta;
15                 }
16                 //绘制背景
17                 e.Graphics.FillRectangle(new SolidBrush(bgColor), e.Bounds);
18                 //绘制文字
19                 e.Graphics.DrawString(lstLog.Items[e.Index].ToString(), e.Font, myBrush, e.Bounds, StringFormat.GenericDefault);
20                 //绘制聚焦框
21                 e.DrawFocusRectangle();
22             }
23         }

猜你喜欢

转载自www.cnblogs.com/masonlu/p/10078612.html