Ger*_*and 4 c# treeview winforms
我有一个3层的树视图.我已经在每个组级别添加了它拥有的子项数.现在我想用不同的颜色或粗体设置该数字.
例:
树[3]
| _ firstGroup [2]
| _ firstChild
| _ secondChild
| _ secondGroup [1]
| _ thirdChild
这是一个Windows窗体应用程序.我认为这是不可能的,但我想确定.
我认为您可以通过将TreeView控件的DrawMode设置为OwnerDrawText来执行此操作,并在DrawNode
事件处理程序中执行绘图.
DrawNode实现的示例(在空间分割节点字符串,以粗体绘制第一个元素,使用常规字体绘制字符串的其余部分,如果没有空格,我们让操作系统执行绘图):
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;
}
}
Run Code Online (Sandbox Code Playgroud)
注意:您可能希望将变量或属性添加到包含粗体字体的表单,而不是为绘制的每个TreeNode重新创建和处理它.