当col / row设置为不可见时,TablelayoutPanel不会调整大小

时间:2015-06-16 17:18:42

标签: c# winforms resize autosize tablelayoutpanel

假设我们TableLayoutPanel有两列:左右列,设计如下

enter image description here

2个文本框'Dock设置为Top(填充将对我在下面描述的内容产生相同的效果)。

根据不同的情况,我希望一列不可见,另一列占用所有空间。我尝试通过设置left.Visible = falseright.Visible = false;

来实现此目的

在对表格进行不同的布局设置尝试后,我无法实现此目的:

  1. 第1列自动调整大小,第2列自动调整大小
  2. 设置R ight.Visible = false时,这就是我的意思 剩下。左边不占用所有空间。

    enter image description here

    正确(左边设置为不可见)。

    enter image description here

    Right占据了所有空间,但Left没有。

    1. 第1列100%和第2列自动调整大小
    2. enter image description here

      enter image description here

      1. 第1列自动调整大小,第2列100%
      2. enter image description here

        enter image description here

        1. 左50%和右50%也不起作用。两者只占用了一半的空间。
        2. 当另一个不可见时,我怎样才能让它们占据所有空间?还有其他方法可以达到这个目的吗?

          谢谢大家。

1 个答案:

答案 0 :(得分:1)

我相信使用SizeType.AutoSize结合使用Anchor属性而不是Dock属性会为您提供所需内容。具体来说,您要设置textBox.Anchor = AnchorStyles.Left | AnchorStyles.Right

如果表格布局面板对于两个文本框都不够宽,则会产生副作用,即首先使右侧文本框溢出表格布局面板的边界。除了确保首先将所有内容初始化为良好的大小值之外,仍然不确定如何解决该问题。

我使用以下LINQPad查询进行了测试:

var textBoxLeft = new TextBox();
textBoxLeft.Anchor = AnchorStyles.Left | AnchorStyles.Right;
textBoxLeft.Text = "Left";
textBoxLeft.AutoSize = true;
textBoxLeft.SizeChanged += (s, e) => textBoxLeft.Text = "Left: " + textBoxLeft.Size.Width;

var textBoxRight = new TextBox();
textBoxRight.Anchor = AnchorStyles.Left | AnchorStyles.Right;
textBoxRight.Text = "Right";
textBoxRight.AutoSize = true;
textBoxRight.SizeChanged += (s, e) => textBoxRight.Text = "Right: " + textBoxRight.Size.Width;

var tableLayoutPanel = new TableLayoutPanel();
tableLayoutPanel.Controls.Add(textBoxLeft, 0, 0);
tableLayoutPanel.Controls.Add(textBoxRight, 1, 0);
tableLayoutPanel.RowStyles.Add(new RowStyle(SizeType.Percent, 100.0f));
tableLayoutPanel.ColumnStyles.Add(new ColumnStyle(SizeType.AutoSize, 100.0f));
tableLayoutPanel.ColumnStyles.Add(new ColumnStyle(SizeType.AutoSize, 100.0f));
tableLayoutPanel.BorderStyle = BorderStyle.FixedSingle;

var buttonLeft = new Button();
buttonLeft.Text = "Toggle Left";
buttonLeft.Click += (s, e) => textBoxLeft.Visible = !textBoxLeft.Visible;

var buttonRight = new Button();
buttonRight.Text = "Toggle Right";
buttonRight.Click += (s, e) => textBoxRight.Visible = !textBoxRight.Visible;

var hostPanel = new FlowLayoutPanel { FlowDirection = FlowDirection.TopDown };
hostPanel.Controls.Add(tableLayoutPanel);
hostPanel.Controls.Add(buttonLeft);
hostPanel.Controls.Add(buttonRight);
hostPanel.Dump();