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 に答える