你如何让AutoSize立即发生?

时间:2017-08-24 13:49:09

标签: c# winforms

问题

我正在动态地向WinForm添加按钮。当我这样做时,我正在重新定位现有的按钮以防止重叠。 AutoSize属性用于自动设置Width

对于较长的文本(将按钮推到默认Width之外),以下代码不起作用。

例如:

  • b.WidthAutoSize设置
  • 之前为75 设置b.Width
  • AutoSize为75
  • 当移动其他按钮时,它会将它们移动b.Width + buffer = 83
  • 然而,在addButton()完成后,AutoSize启动并将宽度设置为150,与下一个按钮重叠,后者仅为83像素而不是158。

Here is a picture demonstrating the result

AutoSize似乎更难以改变控件的大小而无法使用它。我怎样才能立即实现?

尝试1 - 代码

public void addButton(string text)
{
    const int buffer = 8;

    //Construct new button
    Button b = new Button();
    b.Text = text;
    b.AutoSize = true;
    b.Location = new Point(0, 0);

    //Shift over all other buttons to prevent overlap
    //b.Width is incorrect below, because b.AutoSize hasn't taken effect
    for (int i = 0; i < Controls.Count; i++)
        if (Controls[i] is Button)
            Controls[i].Location = new Point(Controls[i].Location.X + b.Width + buffer, Controls[i].Location.Y);

    Controls.add(b);
}

尝试2

搜索Google和StackOverflow以获取以下信息:

  • c#立即自动调整
  • c#autosize fast
  • c#autosize not working

尝试3

在这里问。

最后的度假胜地

如果没有其他工作,可以设置一个计时器来重新定位每个刻度线上的按钮。然而,这是非常草率的设计,并没有帮助学习AutoSize的错综复杂。如果可能的话,我想避免这种解决方法。

3 个答案:

答案 0 :(得分:1)

仅当控件是另一个控件或表单的父级时才应用AutoSizeAutoSizeMode模式。

首先调用

Controls.Add(b);

现在b.Size会相应调整,并可用于计算。

或者,代替Size属性,您可以使用GetPreferredSize方法获取正确的大小,而无需实际应用AutoSize并在计算中使用它:

var bSize = b.GetPreferredSize(Size.Empty);

//Shift over all other buttons to prevent overlap
//b.Width is incorrect below, because b.AutoSize hasn't taken effect
for (int i = 0; i < Controls.Count; i++)
    if (Controls[i] is Button)
        Controls[i].Location = new Point(Controls[i].Location.X + bSize.Width + buffer, Controls[i].Location.Y);

答案 1 :(得分:1)

FlowLayoutPanel控件可以帮到您。

在表单上放置一个,然后尝试按以下方式添加按钮:

Button b = new Button();
b.AutoSize = true;
b.Text = text;
flowLayoutPanel1.SuspendLayout();
flowLayoutPanel1.Controls.Add(b);
flowLayoutPanel1.Controls.SetChildIndex(b, 0);
flowLayoutPanel1.ResumeLayout();

答案 2 :(得分:0)

您可以订阅添加的最后一个按钮的Resize事件。这将允许您准确地更改所有按钮的位置,因为现在所有按钮都已自动调整大小。

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();

        var button1 = NewButton(0);
        button1.Location = new Point(10, 10);

        var button2 = NewButton(1);
        button2.Location = new Point(button1.Right, 10);

        var button3 = NewButton(2);
        button3.Location = new Point(button2.Right, 10);

        button3.Resize += (s, e) =>
        {
            button2.Location = new Point(button1.Right, 10);
            button3.Location = new Point(button2.Right, 10);
        };

        Controls.Add(button1);
        Controls.Add(button2);
        Controls.Add(button3);
    }

    private Button NewButton(int index)
    {
        return new Button()
        {
            Text = "ButtonButtonButton" + index.ToString(),
            AutoSize = true
        };
    }
}