Treenode文字不同的彩色字 [英] Treenode text different colored words
问题描述
我有一个 TreeView
,它的每个 Node.Text
有两个单词。
第一个和第二个单词应该有不同的颜色。我已经改变文本的颜色与 DrawMode
属性和 DrawNode
事件,但我不能如何用两种不同的颜色分割 Node.Text
。有人指出我可以使用 TextRenderer.MeasureText
但我没有idead如何/在哪里使用它。
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.
有人有想法吗?
代码: b
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);
}
推荐答案
>
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);
}
}
}
您必须管理 State
的节点执行适当的操作。
You must manage State
of node to do appropriated actions.
UPDATE
对不起,我的错误看到更新版本。没有必要测量空间大小,因为它已经包含在 texts [0]
。
Sorry, my mistake see updated version. There is no necessary to measure space size because it already contains in texts[0]
.
这篇关于Treenode文字不同的彩色字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!