WinForms:动态更改列表框文本颜色的最简单方法? [英] WinForms: Simplest way to change listbox text color on the fly?

查看:57
本文介绍了WinForms:动态更改列表框文本颜色的最简单方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Looking for a simple way to add color text (or bold text) to a listbox item (the solutions I've seen in Stackoverflow have seemed overly complicated for my needs).

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

I've been adding comments to my listbox via this code:

listBox1.Items.Add("Test complete!");

这行代码贯穿我的代码.我希望能够用颜色来修改偶然的文本,以使诸如测试完成!"这样的行成为可能.显示为绿色.

This line is peppered throughout my code. I'd love to be able to modify the occasional text with color such that a line like "Test complete!" shows up in green.

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

Is there a simple, on-the-fly solution to this?

推荐答案

您可以花一些

You can but takes a little a bit of work to setup, not really that complicated if you are just looking to setup the font color or font.

您必须在DrawItem事件中添加一个处理程序.

You have to add a handler to the DrawItem event.

this.listBox1.DrawItem += new DrawItemEventHandler(listBox1_DrawItem);

这是一个非常简单的处理程序,可以满足您的需求.

and here is a pretty simple handler that does what you are looking for.

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即可.

and then to add items to the ListBox you can do this.

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

我认为很简单.

这篇关于WinForms:动态更改列表框文本颜色的最简单方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆