c#在FlowLayoutPanel上分配一个按钮自定义位置

时间:2014-05-26 17:40:06

标签: c# winforms flowlayoutpanel

我有一个FlowLayoutPanel,我有一些Buttons垂直排序(面板按照我想要的方式自动排序)。但是现在我想放置另一个button1但是有一个自定义位置(位于FlowLayoutPanel的右上角)。到目前为止,我尝试button1.Location = new Point(x,y);,但button1仍然按顺序排列。你能帮助我吗?感谢

1 个答案:

答案 0 :(得分:1)

如果您想将控件放在所需位置,则表示您使用的是错误的容器。 FlowLayouPanel顾名思义,它以流动的方式安排孩子。

使用简单Panel或创建自定义LayoutEngine

要回答您的另一个问题:要垂直放置按钮,您可以执行此操作。

Point location = Point.Empty;
foreach (Button button in buttons)
{
    button.Location = location;
    location.Y += button.Height;
    location.Y += 10;//Add some space
}

另一种方法是使用FlowLayoutPanel的后代并覆盖OnLayout这样的方法。

public class MyFlowLayoutPanel : FlowLayoutPanel
{
    protected override void OnLayout(LayoutEventArgs levent)
    {
        base.OnLayout(levent);

        var button = flowLayout.Controls.OfType<Button>().FirstOrDefault();
        if (button != null)
            button.Location = new Point(flowLayout.Width - button.Width, 0);
    }
}