大胆的treeview节点被截断 - 官方修复将无法工作,因为构造函数中的代码

时间:2012-10-23 17:06:48

标签: c# winforms treeview

我遇到了一个众所周知的问题,即在将TreeNode的字体设置为粗体后,TreeNode的文本会被截断。但是,我相信我已经找到了一种所有普遍接受的"修复"无法工作。

常见解决方案: http://support.microsoft.com/kb/937215

node.NodeFont = new System.Drawing.Font(node.NodeFont, FontStyle.Bold);
node.Text += string.Empty;

变体1: C# Winforms bold treeview node doesn't show whole text(参见BlunT的回答)

node.NodeFont = new System.Drawing.Font(node.NodeFont, FontStyle.Bold);
node.Text = node.Text;

变体2: http://social.msdn.microsoft.com/Forums/en/csharpgeneral/thread/acb877a6-7c9d-4408-aee4-0fb7db127934

node.NodeFont = new System.Drawing.Font(node.NodeFont, FontStyle.Bold);
treeView1.BackColor = treeView1.BackColor;      

以上修复不起作用的情况:

如果将节点设置为粗体的代码位于构造函数中(表单中的一个,或者在本例中为用户控件),则修复程序将不起作用:

public partial class IncidentPlanAssociations : UserControl
{
    public IncidentPlanAssociations()
    {
        InitializeComponent();

        TreeNode node = new TreeNode("This is a problem.");
        node.NodeFont = new Font(treeView1.Font, FontStyle.Bold);
        treeView1.Nodes.Add(node);

        // This does not fix problem
        node.Text += string.Empty;

        // This does not fix problem
        node.Text = node.Text;

        // This does not fix problem
        treeView1.BackColor = treeView1.BackColor;

    }
}

但是,如果我放置这三个中的任何一个"修复"在一个按钮后面的代码中,并在一切运行后单击它将工作得很好。我确定这与最初绘制树视图时的某些事情有关,但我试图找到一个好方法。有什么建议吗?

4 个答案:

答案 0 :(得分:8)

感谢@Robert Harvey的帮助。

如果有人遇到类似的问题,这里的解决方法是将代码从构造函数移动到用户控件的Load事件。上述三种变体中的任何一种都可以使用。

我个人选择了:

private void IncidentPlanAssociations_Load(object sender, EventArgs e)
{
    TreeNode node = new TreeNode("This is no longer a problem.");
    node.NodeFont = new Font(treeView1.Font, FontStyle.Bold);
    treeView1.Nodes.Add(node);

    // This fixes the problem, now that the code 
    //      is in the Load event and not the constructor
    node.Text = node.Text;

}

代码只需要在Load事件中,而不是在此变通方法的构造函数中,以使众所周知的错误正常工作。

答案 1 :(得分:0)

如果您将要使用的最大字体(粗体和/或最大点大小)分配给基本TreeView控件,则显式将字体更改为标准尺寸行的较小字体,您不会有截断问题。

此外,如果您选择最大的字体并且距离标准字体不太远,那么所有内容都会间隔很好。

答案 2 :(得分:0)

在任何视觉变化中使用treeView.BeginUpdate()和treeView.EndUpdate()。

示例:

this.treeView.BeginUpdate();
this.treeView.Nodes.Clear();
this.treeView.Nodes.AddRange(allNodes.ToArray());
this.treeView.EndUpdate();

答案 3 :(得分:0)

我知道这是一篇非常古老的帖子,但我找到了一个适用于我的解决方案,我发现HERE。显然,通过将背景颜色设置为空,它可以解决Bolded文本被截断的问题。

以下是修复:

treeView.BackColor = Color.Empty;