繁体   English   中英

自动定位控件(无TableLayoutPanel)

[英]Auto positioning controls (without TableLayoutPanel)

我的问题在图片中:

位置

我如何在没有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;
}

首先,记录TextBoxLabel之间的间隙,然后将AutoSize设置为true ,然后设置Label的新内容,最后可以相应地移动TextBox

之前:

之前

后:

后

如果您需要对齐多个TextBox ,或宽度TextBox为好,这将是比较复杂的,但你可以按照类似的逻辑。

但是,您必须编写自己的代码,但不能在“设计”视图中使用代码,因为控件的“ Anchor ”位于父容器而非兄弟控件上。 好吧,在Mac上的Xcode ,您可以执行此操作,但是AFAIK Visual Studio没有开箱即用的功能。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM