Gerbrand
Gerbrand

Reputation: 5434

c# set a treenode text in 2 colors

I've got a treeview that is populated in 3 levels. I've added in each group level the number of childs it has. Now I want to set the that number in a different color or in bold.

Example:

tree [3]
|_ firstGroup [2]
  |_ firstChild
  |_ secondChild
|_ secondGroup [1]
  |_ thirdChild

this is a windows forms application. I think it isn't possible, but I want to be sure.

Upvotes: 5

Views: 5388

Answers (2)

Fredrik Mörk
Fredrik Mörk

Reputation: 158389

I think you can do this by setting the TreeView control's DrawMode to OwnerDrawText, and perform the drawing inside a DrawNode event handler.

Sample of DrawNode implementation (split the node string at space, draw the first element in bold, the rest of the string using regular font and if there is no space, we let the OS do the drawing instead):

private void TreeView_DrawNode(object sender, DrawTreeNodeEventArgs e)
{
    string regex = @"^.*\s+\[\d+\]$";
    if (Regex.IsMatch(e.Node.Text, regex, RegexOptions.Compiled))
    {
        string[] parts = e.Node.Text.Split(' ');
        if (parts.Length > 1)
        {
            string count = parts[parts.Length - 1];
            string text = " " + string.Join(" ", parts, 0, parts.Length - 1);
            Font normalFont = e.Node.TreeView.Font;

            float textWidth = e.Graphics.MeasureString(text, normalFont).Width;
            e.Graphics.DrawString(text, 
                                  normalFont, 
                                  SystemBrushes.WindowText, 
                                  e.Bounds);

            using (Font boldFont = new Font(normalFont, FontStyle.Bold))
            {
                e.Graphics.DrawString(count, 
                                      boldFont, 
                                      SystemBrushes.WindowText,
                                      e.Bounds.Left + textWidth, 
                                      e.Bounds.Top); 
            }
        }
    }
    else
    {
        e.DrawDefault = true;
    }
}

Note: you may want to add a variable or property to the form that holds the bold font instead of recreating and disposing it for each TreeNode that is drawn.

Upvotes: 10

uriDium
uriDium

Reputation: 13440

If this functionality is something that you really need then you can extend the TreeView control. As far as I can see it is not sealed.

Upvotes: 0

Related Questions