如何在C#WinForms中为Listbox/ListView行的部分着色?

Mad*_*Boy 8 c# listview listbox colors winforms

  1. 有没有办法为ListBox项目的部分(不仅是整行)着色?例如,列表框项目由5个单词组成,只有一个是彩色的,或者是5个中的3个.
  2. 有没有办法对ListView做同样的事情?(我知道ListView可以按列着色,但我希望在一列中有多种颜色).

我只对免费的解决方案感兴趣,并且希望它们不会很难实现或改变当前的使用情况(引入彩色ListBox代替普通的更好的努力).

带着敬意,

疯狂的男孩

Jef*_*ffH 17

本文介绍如何使用ListBox的DrawItem,并将DrawMode设置为OwnerDraw值之一.基本上,你做这样的事情:

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);
}
Run Code Online (Sandbox Code Playgroud)

而不是单个DrawString调用,将listBox1.Items [e.Index] .ToString()拆分为单词,并为每个单词单独调用DrawString.你必须用每个单词的x,y位置或边界矩形替换e.bounds.

相同的方法应该适用于ListView.