C#Listbox.DrawItem为每一行着色

我有一些代码来改变listbox的行为方式。 我可以更改文本的颜色,但我无法更改每行背景的颜色。

这是我的每一行的for循环

LBLines是全局变量中的字符串存储数组

if (LBLines[e.Index] != "None") { e.Graphics.FillRectangle(new SolidBrush(Color.FromName(LBLines[e.Index])), e.Bounds.X,e.Bounds.Y,e.Bounds.Width,e.Bounds.Height); } 

这将为每条相同颜色的线条着色,即使是那些列为“无”的线条,您需要的是它们保持与默认背景颜色相同的颜色。

编辑:Comparaison不是问题,问题来自e.Graphics.FillRectangle。 它似乎为所有线条空间着色,无论我绘制的是什么。

EDIT2:修改后的代码,表明h等于e.Index

很难说没有更多的代码周围的环境(循环,方法,……),但这段代码做了我认为你想要的:

 public partial class Form1 : Form { string[] Colors { get; set; } public Form1() { InitializeComponent(); Colors = new string[] { "red", "blue", "white", "none", "orange" }; listBox1.Items.AddRange(Colors); } private void listBox1_DrawItem(object sender, DrawItemEventArgs e) { e.DrawBackground(); if (Colors[e.Index] != "none") { using (var brush = new SolidBrush(Color.FromName(Colors[e.Index]))) { e.Graphics.FillRectangle(brush, e.Bounds); } } e.Graphics.DrawString(Colors[e.Index], Font, SystemBrushes.ControlText, e.Bounds); } } 

请注意, ListBoxDrawStyle属性设置为OwnerDrawFixed