WinForms:动态更改列表框文本颜色的最简单方法?

blo*_*djr 3 c# text listbox colors winforms

寻找一种简单的方法来将彩色文本(或粗体文本)添加到列表框项目(我在 Stackoverflow 中看到的解决方案对于我的需求来说似乎过于复杂)。

我一直通过以下代码向我的列表框添加评论:

listBox1.Items.Add("Test complete!");
Run Code Online (Sandbox Code Playgroud)

这行代码贯穿于我的代码中。我希望能够用颜色修改偶尔的文本,例如“测试完成!”之类的行。显示为绿色。

有没有一个简单的即时解决方案?

Bil*_*hir 5

您可以,但需要一些工作来设置,如果您只是想设置字体颜色或字体,那么实际上并没有那么复杂。

您必须向 DrawItem 事件添加一个处理程序。

this.listBox1.DrawItem += new DrawItemEventHandler(listBox1_DrawItem);
Run Code Online (Sandbox Code Playgroud)

这是一个非常简单的处理程序,可以完成您正在寻找的任务。

void listBox1_DrawItem(object sender, DrawItemEventArgs e)
{
    Graphics g = e.Graphics;
    Dictionary<string, object> props = (this.listBox1.Items[e.Index] as Dictionary<string, object>);
    SolidBrush backgroundBrush = new SolidBrush(props.ContainsKey("BackColor") ? (Color)props["BackColor"] : e.BackColor);
    SolidBrush foregroundBrush = new SolidBrush(props.ContainsKey("ForeColor") ? (Color)props["ForeColor"] : e.ForeColor);
    Font textFont = props.ContainsKey("Font") ? (Font)props["Font"] : e.Font;
    string text = props.ContainsKey("Text") ? (string)props["Text"] : string.Empty;
    RectangleF rectangle = new RectangleF(new PointF(e.Bounds.X, e.Bounds.Y), new SizeF(e.Bounds.Width, g.MeasureString(text, textFont).Height));

    g.FillRectangle(backgroundBrush, rectangle);
    g.DrawString(text, textFont, foregroundBrush, rectangle);

    backgroundBrush.Dispose();
    foregroundBrush.Dispose();
    g.Dispose();
}
Run Code Online (Sandbox Code Playgroud)

然后要将项目添加到列表框,您可以执行此操作。

this.listBox1.Items.Add(new Dictionary<string, object> { { "Text", "Something, something"},
                                                         { "BackColor", Color.Red },
                                                         { "ForeColor", Color.Green}});
this.listBox1.Items.Add(new Dictionary<string, object> { { "Text", "darkside!!" },
                                                         { "BackColor", Color.Blue },
                                                         { "ForeColor", Color.Green },
                                                         { "Font", new Font(new Font("Arial", 9), FontStyle.Bold) } });
Run Code Online (Sandbox Code Playgroud)

我认为相当简单。

多田