问题
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);
}
回答1:
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]
.
来源:https://stackoverflow.com/questions/13824052/treenode-text-different-colored-words