日期:2014-05-18 浏览次数:21288 次
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
listBox1.DrawMode = DrawMode.OwnerDrawFixed;//设置ListBox中每一项都手动绘制
listBox1.Items.Add("成功");
listBox1.Items.Add("失败");
listBox1.Items.Add("事业");
listBox1.Items.Add("成仁");
}
//绘制ListBox项的方法
private void listBox1_DrawItem(object sender, DrawItemEventArgs e)
{
listBox1.DrawMode = DrawMode.OwnerDrawFixed;
e.DrawBackground();
Brush myBrush = Brushes.Black;
switch (listBox1.Items[e.Index].ToString())
{
case "成功":
myBrush = Brushes.Blue;
Console.WriteLine(listBox1.Items[e.Index].ToString());
break;
case "失败":
myBrush = Brushes.Red;
Console.WriteLine(listBox1.Items[e.Index].ToString());
break;
default:
myBrush = Brushes.Purple;
Console.WriteLine(listBox1.Items[e.Index].ToString());
break;
}
e.Graphics.DrawString(listBox1.Items[e.Index].ToString(), e.Font, myBrush, e.Bounds, StringFormat.GenericDefault);
e.DrawFocusRectangle();
}
}
------解决方案--------------------
设置listbox.DrawMode属性为OwnerDrawFixed
然后添加listbox到drawitem事件
在里面选择哪个item颜色自己设置
private void listBox1_DrawItem(object sender, DrawItemEventArgs e)
{
listBox1.DrawMode = DrawMode.OwnerDrawFixed;
// Draw the background of the ListBox control for each item.
e.DrawBackground();
// Define the default color of the brush as black.
Brush myBrush = Brushes.Black;
// Determine the color of the brush to draw each item based on the index of the item to draw.
switch (e.Index)
{
case 0:
myBrush = Brushes.Red;
break;
case 1:
myBrush = Brushes.Orange;
break;
case 2:
myBrush = Brushes.Purple;
break;
}
// Draw the current item text based on the current Font and the custom brush settings.
e.Graphics.DrawString(listBox1.Items[e.Index].ToString(), e.Font, myBrush, e.Boun