C # set treenode text in 2 colors

I have a tree structure filled with three levels. I added at each level of the group the number of children that she has. Now I want to set this number to a different color or bold.

Example:

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

This application is for windows forms. I think this is impossible, but I want to be sure.

+3
source share
2 answers

, , TreeView DrawMode OwnerDrawText DrawNode .

DrawNode ( node , , , , ):

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;
    }
}

. , , TreeNode.

+8

, TreeView. , .

0

Source: https://habr.com/ru/post/1715421/


All Articles