我在应用程序中使用树视图(Windows 窗体),该应用程序在加载时有显示粗体文本的奇怪倾向:
当树视图完全加载时,文本显示正常:
我想防止文本在加载过程中变粗。
因此,提供一些技术背景信息:我用于树视图的是 TreeviewDrawMode -> OwnerDrawText :
trvScheduling.DrawMode = TreeViewDrawMode.OwnerDrawText;
在树视图 OnDrawNode 事件中我使用以下代码:
protected override void OnDrawNode(DrawTreeNodeEventArgs e)
{
if (e.Node == null) return;
if (e.Node.IsVisible == false) return;
var selected = (e.State & TreeNodeStates.Selected) == TreeNodeStates.Selected;
//var unfocused = !e.Node.TreeView.Focused;
if (e.Node.TreeView.CheckBoxes == false)
{
// we need to do owner drawing only on a selected node
// and when the treeview is unfocused, else let the OS do it for us
if (selected)
{
var font = e.Node.NodeFont ?? e.Node.TreeView.Font;
Brush solidBrush = new SolidBrush(WinFormsUITheme.styleColor);
e.Graphics.FillRectangle(solidBrush, e.Bounds);
TextRenderer.DrawText(e.Graphics, e.Node.Text, font, e.Bounds, Color.White, TextFormatFlags.GlyphOverhangPadding);
}
else
{
e.DrawDefault = true;
}
}
else
{
//if (e.Node == null) return;
if ((e.State & TreeNodeStates.Selected) != 0)
{
var font = e.Node.NodeFont ?? e.Node.TreeView.Font;
Brush solidBrush = new SolidBrush(Color.White);
e.Graphics.FillRectangle(solidBrush, new Rectangle(e.Bounds.Left, e.Bounds.Top, e.Bounds.Right, 16));
}
//Use the default background and node text.
else
{
//e.DrawDefault = true;
}
// If a node tag is present, draw its string representation
// to the right of the label text.
if (e.Node.ToolTipText != null)
{
//e.Node.Text
int color;
bool isValidInt = int.TryParse(e.Node.ToolTipText.ToString(), out color);
if (isValidInt)
{
Brush colorBrush = new SolidBrush(Color.FromArgb(color));
//e.Graphics.FillRectangle(colorBrush, new Rectangle(e.Bounds.Right + 2, e.Bounds.Top, 10, 10));
e.Graphics.FillRectangle(colorBrush, new Rectangle(e.Bounds.Left + 2, e.Bounds.Top + 2, 10, 10));
e.Graphics.DrawString(e.Node.Text.ToString(), tagFont,
Brushes.Black, e.Bounds.Left + 12, e.Bounds.Top);
}
else
{
e.DrawDefault = true;
}
}
}
}
我想知道 OnDrawNode 事件中是否出现“错误”,导致在加载树视图期间出现这些“粗体”文本。 有谁知道这是什么原因造成的吗?
我尝试在“e.Graphics.DrawString(..”方法之前应用:“e.Graphics.TextRenderingHint = TextRenderingHint.AntiAlias”,但这并不能解决问题。但是,如果我在 OnDrawNode 事件中设置调试断点我注意到树视图绘制每个节点文本三次。第一次文本设置正确,但第二轮文本变为粗体,因为相同的文本被渲染两次。有谁知道如何防止在 OnDrawNode 事件中发生这种情况?
谢谢洛克6。我在 OnDrawNode 事件中绘制了另一个矩形,其大小代表节点边界:
e.Graphics.FillRectangle(new SolidBrush(Color.Black), new Rectangle(e.Bounds.Left, e.Bounds.Top, e.Bounds.Width, e.Bounds.Height));
...这确实显示节点文本超出了边界(因为彩色矩形):
所以你说这就是粗体文本的原因? 如何防止文本超出范围? 也许在 OnDrawNode 事件中使用较小的字体(然后是原始设置的字体)?
顺便说一下,我尝试在 OnDrawNode 事件中绘制文本之前应用此方法:
"e.Graphics.TextRenderingHint = TextRenderingHint.AntiAliasGridFit"
...但这并没有解决问题。