日期:2014-05-17 浏览次数:20436 次
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
var listBox1 = new MyListBox();
listBox1.Items.Add("红色");
listBox1.Items.Add("黄色");
listBox1.Items.Add("蓝色");
listBox1.ItemColors[0] = Color.Red;
listBox1.ItemColors[1] = Color.Yellow;
listBox1.ItemColors[2] = Color.Blue;
Controls.Add(listBox1);
}
}
public class MyListBox : ListBox
{
public MyListBox()
{
ItemColors = new Dictionary<int, Color>();
DrawMode = DrawMode.OwnerDrawFixed;
}
public Dictionary<int, Color> ItemColors { get; private set; }
protected override void OnDrawItem(DrawItemEventArgs e)
{
e.Graphics.FillRectangle(new SolidBrush(e.BackColor), e.Bounds);
var color = ItemColors.ContainsKey(e.Index) ? ItemColors[e.Index] : e.ForeColor;
e.Graphics.DrawString(Items[e.Index].ToString(), e.Font, new SolidBrush(color), e.Bounds);
e.DrawFocusRectangle();
}
}