2

I need to have the text within a node in TreeView to be colored within words or characters. Is that possible? What is the way to go? I heard of Custom Drawing but have no experience with it!

Dumbo
  • 13,555
  • 54
  • 184
  • 288

1 Answers1

8

Set the property of the TreeView:

treeView1.DrawMode = TreeViewDrawMode.OwnerDrawText;

Then from the DrawNode event:

private void treeView1_DrawNode(object sender, DrawTreeNodeEventArgs e) {
  Color nodeColor = Color.Red;
  if ((e.State & TreeNodeStates.Selected) != 0)
    nodeColor = SystemColors.HighlightText;

  TextRenderer.DrawText(e.Graphics,
                        e.Node.Text,
                        e.Node.NodeFont,
                        e.Bounds,
                        nodeColor,
                        Color.Empty,
                        TextFormatFlags.VerticalCenter);
}

More from MSDN: TreeView.DrawNode Event

LarsTech
  • 80,625
  • 14
  • 153
  • 225
  • How could I change this so half of the node.text is red and the other half is of default color (black) – phadaphunk Dec 11 '12 at 15:39
  • @PhaDaPhunk Which half? Do you mean two words? One red, one black? – LarsTech Dec 11 '12 at 15:40
  • Yes exactly it would be two words. There could be a split character between them like '-' if necessary – phadaphunk Dec 11 '12 at 15:46
  • 1
    @PhaDaPhunk It would require calling TextRenderer twice with some measurements in-between. TextRenderer has a static MeasureText function. Too much code for a comment. If you need help with it, try posting it as a question. – LarsTech Dec 11 '12 at 15:59
  • ok i'm sure this is the bit of info I was missing thanks a lot ! – phadaphunk Dec 11 '12 at 16:00
  • I posted it as a question right here : http://stackoverflow.com/questions/13824052/treenode-text-different-colored-words Thanks for your help – phadaphunk Dec 11 '12 at 16:17