Way to color parts of the Listbox/ListView line in C# WinForms?

吃可爱长大的小学妹 提交于 2019-11-29 06:52:53

This article tells how to use DrawItem of a ListBox with DrawMode set to one of the OwnerDraw values. Basically, you do something like this:

listBox1.DrawMode = OwnerDrawFixed;
listBox1.DrawItem += new System.Windows.Forms.DrawItemEventHandler(this.listBox1_DrawItem);

private void listBox1_DrawItem(object sender, DrawItemEventArgs e)
{
e.DrawBackground();
e.DrawFocusRectangle();
// TODO: Split listBox1.Items[e.Index].ToString() and then draw each separately in a different color
e.Graphics.DrawString(listBox1.Items[e.Index].ToString(),new Font(FontFamily.GenericSansSerif, 14, FontStyle.Bold),new SolidBrush(color[e.Index]),e.Bounds);
}

Instead of the single DrawString call, Split listBox1.Items[e.Index].ToString() into words and make a separate call to DrawString for each word. You'll have to replace e.bounds with an x,y location or a bounding rectangle for each word.

The same approach should work for ListView.

There is no built-in API which supports this type of modification to a WinForms ListBox or ListView. It is certainly possible to achieve this but the solution will involve a lot of custom painting and likely overriding WndProc. This will be a very involved and heavy solution.

If this type of experience is important to your application I think you should very seriously consider WPF as a solution. WPF is designed to provide this type of eye candy and there are likely many samples on the web to get you up and running.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!