寻找一种将彩色文本(或粗体文本)添加到列表框项目的简单方法(我在 Stackoverflow 中看到的解决方案似乎对我的需求来说过于复杂)。
我一直在通过这段代码向我的列表框添加评论:
listBox1.Items.Add("Test complete!");
这一行遍及我的代码。我很想能够用颜色修改偶尔的文本,这样一行像“测试完成!”显示为绿色。
是否有一个简单的即时解决方案?
最佳答案
你可以,但需要一点 work设置,如果您只是想设置字体颜色或字体,其实并没有那么复杂。
您必须向 DrawItem 事件添加处理程序。
this.listBox1.DrawItem += new DrawItemEventHandler(listBox1_DrawItem);
这是一个非常简单的处理程序,可以满足您的需求。
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();
}
然后要将项目添加到 ListBox,您可以执行此操作。
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) } });
我觉得很简单。
关于c# - WinForms:即时更改列表框文本颜色的最简单方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29173517/