【发布时间】:2017-11-29 12:59:04
【问题描述】:
【问题讨论】:
-
只保留一个 Y 变量来跟踪最后一个的位置。
【问题讨论】:
您的意思是您希望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 没有开箱即用的此功能。
【讨论】:
这是一个使用计数器来跟踪创建的控件数量并计算正确的 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);
}
【讨论】: