ListBox以彩色插入项目

我使用ListBox插入文本,就像You add Michael in your database一样, You delete Michael ,…

  listBox1.Items.Insert(0,"You add " + name + " in your database\n"); 

它工作正常。 如何将颜色设置为黑色(插入)和红色(删除)? 我试过这个:

  public class MyListBoxItem { public MyListBoxItem(Color c, string m) { ItemColor = c; Message = m; } public Color ItemColor { get; set; } public string Message { get; set; } } private void listBox1_DrawItem(object sender, DrawItemEventArgs e) { MyListBoxItem item = listBox1.Items[e.Index] as MyListBoxItem; // Get the current item and cast it to MyListBoxItem if (item != null) { e.Graphics.DrawString( // Draw the appropriate text in the ListBox item.Message, // The message linked to the item listBox1.Font, // Take the font from the listbox new SolidBrush(item.ItemColor), // Set the color 0, // X pixel coordinate e.Index * listBox1.ItemHeight // Y pixel coordinate. Multiply the index by the ItemHeight defined in the listbox. ); } else { // The item isn't a MyListBoxItem, do something about it } } 

插入时:

  listBox1.Items.Insert(0, new MyListBoxItem(Color.Black, "You add " + name + " in your database\n")); listBox1.Items.Insert(0, new MyListBoxItem(Color.Red, "You delete " + name + "\n")); 

此代码有效,但是当我插入多个项目时,scrol无法正常工作 – 文本不会出现。 我究竟做错了什么? 或者是否有其他方法可以做到这一点?

你应该使用:

 e.Bounds.Top 

代替:

 e.Index * listBox1.ItemHeight 

此外,在绘制文本之前,我建议绘制背景,以便您可以看到选择了哪个项目,列表是否支持选择,或者在任何情况下都支持列表所需的项目背景颜色:

 using (Brush fill = new SolidBrush(e.BackColor)) { e.Graphics.FillRectangle(fill, e.Bounds); } 

并且您应该正确处理您正在创建的画笔以绘制文本。

您是否考虑过在报表视图中使用ListView而不是列表框? 然后,您不必自定义绘图以获取颜色。

将绘图更改为

  e.Graphics.DrawString(item.Message, listBox1.Font, new SolidBrush(item.ItemColor), 0, e.Bounds.Top);