7

我正在使用WinForms在C#中创建一个 GUI 。 我正在尝试将程序化创建的面板放置在另一个下方。由于这些面板的内容可能会根据其内容而有所不同,因此我正在使用让 WinForms 执行正确的大小调整。
Panel.AutoSize

问题是:如果我在填充后立即使用Panel.Height(或) ,则返回的值始终是我的默认值。正如我在启动应用程序时看到的那样,确实会发生调整大小,但我只是不知道什么时候。Panel.Size.HeightPanel

这是我正在做的简化版本:

this.SuspendLayout();

int yPos = 0;
foreach (String entry in entries)
{
    Panel panel = new Panel();
    panel.SuspendLayout();
    panel.AutoSize = true;
    panel.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowOnly;
    panel.BackColor = System.Drawing.SystemColors.Window; // Allows to see that the panel is resized for dispay
    panel.Location = new System.Drawing.Point(0, yPos);
    panel.Size = new System.Drawing.Size(this.Width, 0);
    this.Controls.Add(panel);

    Label label = new Label();
    label.AutoSize = true;
    label.Location = new System.Drawing.Point(0, 0);
    label.MaximumSize = new System.Drawing.Size(panel.Width, 0);
    label.Text = entry;
    panel.Controls.Add(label);

    panel.ResumeLayout(false);
    panel.PerformLayout();

    yPos += panel.Height; // When breaking here, panel.Height is worth 0
    yPos += label.Height; // This works perfectly, label.Height was updated according to the text content when breaking at that point
}

this.ResumeLayout(false);
this.PerformLayout();

所以真正的问题是:如何Panel.Size在添加控件后获取更新,以获得正确的高度值?

注意:我知道我可以使用TextBox高度,但我发现它不优雅且不切实际,因为在我的实际代码中,有更多控件,Panel我需要在下面几行使用该面板高度。

4

1 回答 1

5

我相信正在发生的是,面板的大小将在您对其父级执行 PerformLayout 时确定。SuspendLayout / ResumeLayout您可以通过将面板的父代码移动到循环中来使其按您想要的方式工作。

int yPos = 0;
foreach (String entry in entries)
{
    this.SuspendLayout();
    Panel panel = new Panel();
    panel.SuspendLayout();
    panel.AutoSize = true;
    panel.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowOnly;
    panel.BackColor = System.Drawing.SystemColors.Window; // Allows to see that the panel is resized for dispay
    panel.Location = new System.Drawing.Point(0, yPos);
    panel.Size = new System.Drawing.Size(this.Width, 0);
    this.Controls.Add(panel);

    Label label = new Label();
    label.AutoSize = true;
    label.Location = new System.Drawing.Point(0, 0);
    label.MaximumSize = new System.Drawing.Size(panel.Width, 0);
    label.Text = entry;
    panel.Controls.Add(label);
    panel.ResumeLayout(true);
    this.ResumeLayout(true);
    yPos += panel.Height; // When breaking here, panel.Height is worth 0
    //yPos += label.Height; // This works perfectly, label.Height was updated according to the text content when breaking at that point
}
this.PerformLayout();
于 2013-01-08T06:39:49.833 回答