[英]Auto positioning controls (without TableLayoutPanel)
这是一个使用计数器跟踪创建的控件的数量并计算正确的Y位置的简单示例:
private int counter = 0;
private void button1_Click(object sender, EventArgs e)
{
counter++;
int y = counter * 25;
Label lbl = new Label();
lbl.Text = "Label " + counter.ToString();
lbl.Location = new Point(5, y);
TextBox tb = new TextBox();
tb.Location = new Point(lbl.Bounds.Right + 5, y);
this.Controls.Add(lbl);
this.Controls.Add(tb);
}
您是说要TextBox
根据Label
的宽度左右移动吗?
private void button2_Click(object sender, EventArgs e) {
int gap1 = textBox1.Left - label1.Right;
label1.AutoSize = true;
label1.Text = "long long long long long long long long";
textBox1.Left = label1.Right + gap1;
int gap2 = textBox1.Left - label1.Right;
label2.AutoSize = true;
label2.Text = "s";
textBox2.Left = label2.Right + gap2;
}
首先,记录TextBox
和Label
之间的间隙,然后将AutoSize
设置为true
,然后设置Label
的新内容,最后可以相应地移动TextBox
。
之前:
后:
如果您需要对齐多个TextBox
,或宽度TextBox
为好,这将是比较复杂的,但你可以按照类似的逻辑。
但是,您必须编写自己的代码,但不能在“设计”视图中使用代码,因为控件的“ Anchor
”位于父容器而非兄弟控件上。 好吧,在Mac上的Xcode
,您可以执行此操作,但是AFAIK Visual Studio
没有开箱即用的功能。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.