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

Joe*_*ung 6 c# treeview winforms

我遇到了众所周知的问题,在将TreeNode的字体设置为粗体后,TreeNode的文本被截断.但是,我相信我发现了一种所有普遍接受的"修复"都无法工作的情况.

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

node.NodeFont = new System.Drawing.Font(node.NodeFont, FontStyle.Bold);
node.Text += string.Empty;
Run Code Online (Sandbox Code Playgroud)

变体1: C#Winforms粗体树视图节点不显示全文(参见BlunT的答案)

node.NodeFont = new System.Drawing.Font(node.NodeFont, FontStyle.Bold);
node.Text = node.Text;
Run Code Online (Sandbox Code Playgroud)

变体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;      
Run Code Online (Sandbox Code Playgroud)

以上修复不起作用的场景:

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

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;

    }
}
Run Code Online (Sandbox Code Playgroud)

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

Joe*_*ung 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;

}
Run Code Online (Sandbox Code Playgroud)

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

  • 似乎还需要在将节点添加到treeView控件之后进行.(??) (2认同)