繁体   English   中英

在 C# 中,如何使列表框中的所有项目不更改为我最后设置的颜色?

[英]In C#, how can I keep all my items in a listbox from changing to the color I set last?

我已经研究了如何更改每一行的颜色,这是我使用公共变量 itemColor 的代码,它是一个 Brush

...

public Brush itemColor;

private void button2_Click(object sender, EventArgs e)
{
    itemColor = Brushes.Purple;
    listBox1.Items.Add("Purple");
    itemColor = Brushes.Green;
    listBox1.Items.Add("Green");
    itemColor = Brushes.Red;
    listBox1.Items.Add("Red");
}

private void listBox1_DrawItem(object sender, DrawItemEventArgs e)
{
    e.DrawBackground();
    e.Graphics.DrawString(listBox1.Items[e.Index].ToString(), listBox1.Font, 
                          itemColor, e.Bounds, StringFormat.GenericDefault);
    e.DrawFocusRectangle();
}

...

我已将列表框 DrawMode 设置为 OwnerDrawFixed,并且所有项目都变为红色。 谁能看到我可能很愚蠢的错误?

每次需要重绘控件时都会调用listBox1_DrawItem ,例如在项目添加/删除或选择更改时。 您可以通过向表单添加第二个按钮并执行以下操作来查看这一点:

private void button2_Click(object sender, EventArgs e)
{
    itemColor = Brushes.Blue;
}

单击第二个按钮后,下次重绘ListBox ,所有项目的文本都将变为蓝色。


很可能有一种更好的方法来做到这一点,但您可以处理这个问题的一种方法是创建一个类来表示您的项目与TextBrush字段并添加填充您的列表框。 然后在 DrawItem 处理程序上,您将Items[e.Index]为您的类并引用文本和颜色字段。 像这样的东西:

class Entry
{
    public string Text;
    public Brush Color;
}

private void button1_Click(object sender, EventArgs e)
{
    listBox1.Items.Add(new Entry { Text = "Purple", Color = Brushes.Purple });
    listBox1.Items.Add(new Entry { Text = "Green",  Color = Brushes.Green  });
    listBox1.Items.Add(new Entry { Text = "Red",    Color = Brushes.Red    });
}

private void listBox1_DrawItem(object sender, DrawItemEventArgs e)
{
    var currentItem = listBox1.Items[e.Index] as Entry;

    e.DrawBackground();
    e.Graphics.DrawString(currentItem.Text, listBox1.Font, currentItem.Color,
                          e.Bounds, StringFormat.GenericDefault);
    e.DrawFocusRectangle();
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM