Panel是什么时候?当面板添加控件后,尺寸更新.AutoSize = true
本文关键字:更新 AutoSize true 控件 什么时候 添加 Panel | 更新日期: 2023-09-27 17:51:00
我正在使用WinForms用 c#创建一个GUI。我试图定位程序化创建的面板一个低于另一个。由于这些面板的内容可以根据它们的内容而变化,我使用Panel.AutoSize
来让WinForms执行正确的调整大小。
问题是:如果我在填充Panel
后使用Panel.Height
(或Panel.Size.Height
),则返回的值始终是我的默认值。当启动应用程序时,我可以看到调整大小确实发生了,但我只是不知道何时。
下面是我正在做的事情的简化版本:
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
,我需要使用面板的高度下面几行
我认为发生的是,面板的大小将被确定,当你在其父上执行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();