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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With