列表视图中的多色子项 - 是否可能?

时间:2015-03-18 13:18:45

标签: c# listview

直截了当的问题:是否可以在子项中插入一个字符串,每个字母都有不同的颜色?

我想用颜色表示时间延迟。例: 子项字符串" 10 14 50"值10和50,红色,14,绿色。

1 个答案:

答案 0 :(得分:2)

尝试将OwnerDraw模式设置为true并自行提供绘图例程:

listView1.OwnerDraw = true;
listView1.DrawColumnHeader += listView1_DrawColumnHeader;
listView1.DrawSubItem += listView1_DrawSubItem;

void listView1_DrawColumnHeader(object sender, DrawListViewColumnHeaderEventArgs e) {
  e.DrawDefault = true;
}

void listView1_DrawSubItem(object sender, DrawListViewSubItemEventArgs e) {
  if (e.ColumnIndex == 1) {
    e.Graphics.SetClip(e.Bounds);
    using (SolidBrush br = new SolidBrush(listView1.BackColor)) {
      e.Graphics.FillRectangle(br, e.Bounds);
    }
    int textLeft = e.Bounds.Left;
    string[] subItems = e.Item.SubItems[1].Text.Split(' ');
    for (int i = 0; i < subItems.Length; ++i) {
      int textWidth = TextRenderer.MeasureText(subItems[i], listView1.Font).Width;
      TextRenderer.DrawText(e.Graphics, subItems[i], listView1.Font,
          new Rectangle(textLeft, e.Bounds.Top, textWidth, e.Bounds.Height),
          i == 0 ? Color.Red : i == subItems.Length - 1 ? Color.Green : Color.Black, 
          Color.Empty,
          TextFormatFlags.VerticalCenter | TextFormatFlags.PreserveGraphicsClipping);
      textLeft += textWidth;
    }
    e.Graphics.ResetClip();
  } else {
    e.DrawDefault = true;
  }
}

结果:

enter image description here