C#Listbox.DrawItem为每行着色

C#Listbox.DrawItem为每行着色,c#,listbox,C#,Listbox,我有一些代码来改变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);

我有一些代码来改变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);
}
这将使每一行颜色相同,即使是那些列为“无”的行,但我需要的是它们保持与默认背景色相同的颜色

编辑:比较不是问题,问题来自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);
    }
}

请注意,
ListBox
DrawStyle
属性设置为
OwnerDrawFixed
如果没有更多的代码上下文(循环、方法,…),很难说,但此代码实现了我认为您想要的功能:

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);
    }
}

请注意,
ListBox
DrawStyle
属性设置为
OwnerDrawFixed

我会检查以确保您在LBLines[h]上进行了正确的比较“无”首先`我会检查以确保您在LBLines[h]上进行了正确的比较!=首先是“无”`是的,我删除了循环,但它并没有解决问题。不,似乎所有的行都是背景做的。这很奇怪,因为DrawString工作得很好。这是我的代码(除了变量名),但它不工作。好的,我做了一个更改。你的代码和我的代码之间唯一的区别是我一个接一个地设置了所有的边界,而你,你只是使用了e.bounds。我改变了,现在它工作了。。。wtf?奇怪-即使我把它改成像你那样显式地描述矩形(正如我所期望的那样),我也能工作-但我很高兴你现在能让它工作:-)是的,我删除了循环,但它并没有解决问题。不,似乎背景对所有的线条都起作用。这很奇怪,因为DrawString工作得很好。这是我的代码(除了变量名),但它不工作。好的,我做了一个更改。你的代码和我的代码之间唯一的区别是我一个接一个地设置了所有的边界,而你,你只是使用了e.bounds。我改变了,现在它工作了。。。wtf?奇怪-即使我将其更改为像您那样显式描述矩形(正如我所期望的那样),我的工作仍然有效-但我很高兴您现在能够工作:-)