Treenode文本不同颜色的单词

pha*_*unk 1 c# treeview treenode colors winforms

我有一个TreeView,每个Node.Text都有两个字.第一个和第二个词应该有不同的颜色.我已经用DrawMode属性和DrawNode事件改变了文本的颜色,但我无法弄清楚如何分割Node.Text两种不同的颜色.有人指出我可以使用,TextRenderer.MeasureText但我没有想法如何/在哪里使用它.

有人有想法吗?


代码:

formload()
{
  treeView1.DrawMode = TreeViewDrawMode.OwnerDrawText;
}

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);
}
Run Code Online (Sandbox Code Playgroud)

Ham*_*yan 7

试试这个:

    private void treeView1_DrawNode(object sender, DrawTreeNodeEventArgs e)
    {
        string[] texts = e.Node.Text.Split();
        using (Font font = new Font(this.Font, FontStyle.Regular))
        {
            using (Brush brush = new SolidBrush(Color.Red))
            {
                e.Graphics.DrawString(texts[0], font, brush, e.Bounds.Left, e.Bounds.Top);
            }

            using (Brush brush = new SolidBrush(Color.Blue))
            {
                SizeF s = e.Graphics.MeasureString(texts[0], font);
                e.Graphics.DrawString(texts[1], font, brush, e.Bounds.Left + (int)s.Width, e.Bounds.Top);
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

您必须管理State节点以执行适当的操作.

UPDATE

对不起,我的错误看到了更新版本.没有必要测量空间大小,因为它已经包含在内texts[0].