TreeView with multi-color TreeNode text

2019-05-28 22:48发布

问题:

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!

回答1:

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