问题
我在动态地向WinForm添加按钮。当我这样做时,我正在重新定位现有的按钮,以防止重叠。AutoSize属性用于自动设置Width。
对于较长的文本(按下超出其默认Width的按钮),下面的代码无法工作。
例如:
b.Width之前,AutoSize为75b.Width后,AutoSize为75b.Width + buffer = 83移动。addButton()完成后,AutoSize启动并将宽度设置为150,重叠下一个按钮,该按钮距离仅83像素,而不是158像素。

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中的以下内容:
尝试3
在这里问。
最后度假村
如果没有其他工作,则可以设置一个定时器来重新定位每个滴答的按钮。然而,这是非常草率的设计,无助于学习复杂的AutoSize。如果可能的话,我想避免这种情况。
发布于 2017-08-24 14:58:24
只有当控件父级为另一个控件或窗体时,才会应用AutoSize和AutoSizeMode模式。
所以先调用
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);发布于 2017-08-24 15:07:51
FlowLayoutPanel控件为您执行此操作。
在窗体上放置一个按钮,并尝试以下列方式添加按钮:
Button b = new Button();
b.AutoSize = true;
b.Text = text;
flowLayoutPanel1.SuspendLayout();
flowLayoutPanel1.Controls.Add(b);
flowLayoutPanel1.Controls.SetChildIndex(b, 0);
flowLayoutPanel1.ResumeLayout();发布于 2017-08-24 14:37:17
您可以订阅添加的最后一个按钮的调整大小事件。这将允许您准确地更改所有按钮的位置,因为现在所有的按钮都是AutoSized。
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
};
}
}https://stackoverflow.com/questions/45863371
复制相似问题