我试图找出一种使用StringFormat类向给定的TreeNode
文本添加新行的方法。例如,字符串ID1:123456, ID2:789000,
可以用逗号分隔,并在中间插入一个换行符,因此它有两行。
我知道没有必要将TreeNode
文本分成多行,但这是我的主管所要求的,我别无选择。
我目前的解决方案是重写一个DrawNode
函数,并使用DrawString
函数自定义TreeNode
文本格式,但我的问题是,在这个阶段我不知道如何插入换行符。
private void TreeView_SO_DrawNode(object sender, DrawTreeNodeEventArgs e)
{
e.DrawDefault = false;
string drawString = e.Node.Text;
Font drawFont = ((TreeView)sender).Font;
SolidBrush drawBrush = new SolidBrush(Color.Black);
StringFormat drawFormat = new StringFormat();
// what to put in here to insert a new line?
e.Graphics.DrawString(drawString, drawFont, drawBrush, e.Node.Bounds, drawFormat);
}
更新
谢谢大家的帮助。最后,我发现这很容易,多亏了EskeRahn在带有E.G.多行树内容的上发布的代码。这段代码非常有用;但是,我只需要EskeRnhn代码的一部分来执行我的理想操作。所以我的代码就这样结束了,
private void TreeView_SO_DrawNode(object sender, DrawTreeNodeEventArgs e)
{
e.DrawDefault = false;
string drawString = e.Node.Text;
Font drawFont = ((TreeView)sender).Font;
SolidBrush drawBrush = new SolidBrush(Color.Black);
Rectangle eNodeBounds = NodeBounds(e.Node);
e.Graphics.DrawString(drawString, drawFont, drawBrush, eNodeBounds);
}
private Rectangle NodeBounds(TreeNode node)
{
if (node?.TreeView != null && node?.Text != null && (0 < node.Bounds.Location.X || 0 < node.Bounds.Location.Y))
{
using (Graphics g = node.TreeView.CreateGraphics())
{
SizeF textSize = g.MeasureString(node.Text, node.NodeFont ?? node.TreeView.Font);
return Rectangle.Ceiling(new RectangleF(PointF.Add(node.Bounds.Location,
new SizeF(0, (node.TreeView.ItemHeight - textSize.Height) / 2)),
textSize));
}
}
else
{
return node?.Bounds ?? new Rectangle();
}
}
,这里我根本不需要担心StringFormat
类,因为我已经覆盖了一个DrawNode
函数,所以当我将字符串传递给TreeNode
文本时,我只需要添加换行符。我已经测试了多个案例,这段代码运行良好。
发布于 2022-03-31 22:36:56
您可以用逗号分隔文本,然后使用新行连接。
var splitText = e.Node.Text.Split(new char[] { ',' }, System.StringSplitOptions.RemoveEmptyEntries);
var newString = string.Join(System.Environment.NewLine, splitText);
https://stackoverflow.com/questions/71699669
复制相似问题