Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
379 views
in Technique[技术] by (71.8m points)

c# - Treenode text different colored words

I have a TreeView and each of it's Node.Text has two words. The first and second words should have different colors. I'm already changing the color of the text with the DrawMode properties and the DrawNode event but I can't figure out how to split the Node.Text in two different colors. Someone pointed out I could use TextRenderer.MeasureText but I have no idead how/where to use it.

Someone has an idea ?


Code :

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);
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try this:

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

You must manage State of node to do appropriated actions.

UPDATE

Sorry, my mistake see updated version. There is no necessary to measure space size because it already contains in texts[0].


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...