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

时间:2023-03-09 23:03:18
[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(优先级高)。

         private void lstLog_DrawItem(object sender, DrawItemEventArgs e)
{
if (e.Index >= )
{
e.DrawBackground();
Brush myBrush = Brushes.Black; //前景色
Color bgColor = Color.White; //背景色
if(lstLog.Items[e.Index].ToString().Contains("成功"))
{
bgColor = Color.RoyalBlue;
}
if (lstLog.Items[e.Index].ToString().Contains("失败"))
{
bgColor = Color.Magenta;
}
//绘制背景
e.Graphics.FillRectangle(new SolidBrush(bgColor), e.Bounds);
//绘制文字
e.Graphics.DrawString(lstLog.Items[e.Index].ToString(), e.Font, myBrush, e.Bounds, StringFormat.GenericDefault);
//绘制聚焦框
e.DrawFocusRectangle();
}
}

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