如何在面板 C# 中将按钮设置为最大左侧

How to set a button to a max left in panel c#

我在面板中已有一个按钮,直到滚动才可见(因为面板的视图大小小于按钮 A 的 x 坐标)。我想在 buttonA 之外放置一个按钮。怎么做 ?我正在使用它,但它只将按钮放在控件视图的左侧,而不是内部最大宽度。

我希望它是通用的,如果任何按钮超出最大内部宽度,下一个按钮甚至应该向左移动到该按钮。不能使用停靠点,因为我也想将相同的功能用于顶部放置。

"New edit to question "

按钮是在每次点击后生成的,它们的宽度是随机的。该按钮可以删除,但新按钮应添加到目前占用的最大宽度,如果删除最近的按钮,则下一个按钮应出现在第二个最左边的按钮之后

button1.Left = buttonA.Parent.Size.Width+button1.Width;

如果你想把 button1 放在 buttonA 的右边,那么你可以使用 buttonALeftWidth 属性来实现这个输出:

// Places button1 to the right of buttonA by 10 pixels
button1.Left = buttonA.Left + buttonA.Width + 10;

编辑:

为了确保我总是在最后一个按钮的右侧添加,我可以只保留对最后使用的位置的引用:

// Remember the last Left used. 
// We first set it to the Left of buttonA plus its Width.
int lastLeft = buttonA.Left + buttonA.Width;

// button1 now gets set to this plus a gap of 10 pixels
button1.Left = lastLeft + 10;
// Remember the last position
lastLeft = button1.Left + button1.Width;

// Set next button
button2.Left = lastLeft + 10;
// Remember...
lastLeft = button2.Left + button2.Width;

您可以通过将其中的一些包装在一个方法中来使其更清晰,但为了清楚起见,我保留了冗长的版本。

您可以将按钮的总数 Width 保存为一个整数,并用它来设置 Left 属性:

private void button1_Click(object sender, EventArgs e)
{
    Button btn = new Button();
    btn.Left = nTotalWidth;

    panel1.Controls.Add(btn);
    nTotalWidth += btn.Width;
}

这将在您每次点击 button1 时在上一个按钮旁边创建一个新按钮。