刚添加到容器中时,C#标签大小错误

问题描述 投票:1回答:1

我已经找到了一个解决这个问题的方法,通过使用 TextTenderer.MeasureText但无论如何,我对为什么会发生这种情况感到非常困惑。我这里有一段代码,在标签被添加到flowLayoutPanel之前,标签的首选高度和宽度分别是16和78(这很好)。

var label = new Label() { Name = col.ColumnName, Text = col.ColumnText + ":", AutoSize = true, Margin = new Padding(1, 1, 1, 0), Font = label8.Font };
label.MaximumSize = new Size(148, 0);

Control input = null;
// Do stuff to input but not label

flowLayoutPanel2.Controls.Add(label);
flowLayoutPanel2.Controls.Add(input);
flowLayoutPanel2.Height += label.Height + input.Height + 5;

在标签被添加到flowLayoutPanel之前,标签的首选高度和宽度分别是16和78(这很好),但是在添加标签之后,实际高度和宽度现在是176和16。我不太明白176的高度是怎么来的,但每次都是同一个数字(176)。高度应该是16,但宽度显然是取了这个值。

在面板上添加的所有5个标签和其他5个控件中,只有添加的第二个标签,也就是总共第三个控件出现了这种情况。在添加标签后,程序再次到达图示代码时,标签的大小突然正确了。

如果有人能告诉我发生了什么,那将非常感激。

c# controls flowlayoutpanel
1个回答
0
投票

我相信这是因为当一个Label的父体发生变化时,当AutoSize被设置为true时,它将自行调整大小(取自于 参考源) :

protected override void OnParentChanged(EventArgs e) {
    base.OnParentChanged(e);
    if (SelfSizing) {
        // VSWhidbey 368232: in the case of SelfSizing
        // we dont know what size to be until we're parented
        AdjustSize();
    }
    Animate();
}

同样的事情在Visual Studio Designer中也发生了,如果你把Label放在FlowLayoutPanel中,那么你会看到它的大小会自动更新。

© www.soinside.com 2019 - 2024. All rights reserved.