Ant*_*nry 7 c# size autosize winforms
我正在使用WinForms在C#中创建GUI .
我试图将programaticaly创建的面板放在另一个下面.由于这些面板的内容可能会根据其内容而有所不同,我正在使用WinForms执行正确的大小调整.Panel.AutoSize
问题是:如果我在填充后立即使用Panel.Height(或Panel.Size.Height)Panel,则返回的值始终是我的默认值.调整大小确实发生了,正如我在启动应用程序时所看到的那样,但我只是不知道何时.
这是我正在做的简化版本:
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();
Run Code Online (Sandbox Code Playgroud)
所以真正的问题是:如何Panel.Size在添加控件后获得更新,以获得适当的高度值?
注意:我知道我可以使用TextBox高度,但我发现它不优雅且不切实际,因为在我的实际代码中有更多的控件Panel,我需要使用下面几行的面板高度.
我正在发生的事情是,当您对其Parent执行PerformLayout时,将确定Panel的大小.您可以通过将面板的父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();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9598 次 |
| 最近记录: |