今天有个需求,ListBox中的项,要根据情况设置不同的颜色,有的红色,有的绿色,怎么设置呢?
直接找ListBox的api,没有,ListBox.Item的api,也没有。
想起去年一个项目中做过类似的功能,翻出来,记录如下:
1. 给ListBox的DrawItem方法绑定事件 drawLog
//给ListBox的DrawItem事件绑定一个方法,取名drawLog
lbLog.DrawItem += new DrawItemEventHandler(drawLog);
2. 定义drawLog方法
private void drawLog(Object sender, DrawItemEventArgs e)
{
if (lbLog.Items.Count > 0 && lbLog.Items.Count > e.Index)
{
if (e.Index < 0)
{ return; }
string str = lbLog.Items[e.Index].ToString();
Color foreColor = Color.Black;
//重点,根据item的具体内容决定颜色
if (str.Contains("本次测试PASS")) { foreColor = Color.Green; }
if (str.Contains("本次测试NG")) { foreColor = Color.Red; }
//重点,画上颜色
e.Graphics.DrawString(str, e.Font, new SolidBrush(foreColor), e.Bounds);
}
}
测试发现DrawItem事件没有触发,日志颜色没变化。网上查到了答案:
https://stackoverflow.com/questions/31088713/c-sharp-listbox-drawitem-not-working
要把ListBox的 DrawMode属性设置为 OwnerDrawFixed或者OwnerDrawVariable,才能让DrawItem事件触发。
效果:
问题解决。