使用FlowLayoutPanel进行布局控制

时间:2016-11-28 05:44:57

标签: c# winforms layout flowlayoutpanel

我想在表单的顶部放置一堆按钮,在这些按钮的正下方放置一个SplitContainer。所有这些都是在代码中完成的(不是通过设计者),所以我可以动态地管理按钮的数量和文本。我认为将按钮放入FlowLayoutPanel非常方便,因此当表单调整大小时,他们可以使用流功能进行响应。

我的问题是如何设置SplitContainer布局设置(大小,位置,锚点,停靠等),以确保无论我如何调整表单大小,SplitContainer都在按钮下方(无间隙),它填补了表格的其余部分。以下就是我所做的。

        this.Size = new Size(300, 400);

        string[] tags = new string[] { "action", "romance", "drama", "sci-fi", "horror" };
        FlowLayoutPanel flp = new FlowLayoutPanel();
        flp.Size = new Size(this.Width, 50);
        flp.Location = new Point(0, 0);
        flp.AutoSize = true;
        flp.Anchor = AnchorStyles.Left | AnchorStyles.Right | AnchorStyles.Top;
        flp.FlowDirection = FlowDirection.LeftToRight;
        this.Controls.Add(flp);

        //flp.Resize += flp_Resize;

        foreach (string tag in tags)
        {
            Button btn = new Button();
            btn.Text = tag;
            flp.Controls.Add(btn);
        }

        SplitContainer sc = new SplitContainer();
        ListBox lb = new ListBox(); lb.Dock = DockStyle.Fill; lb.Parent = sc.Panel1; lb.Items.Add("test");
        PictureBox pb = new PictureBox(); pb.Dock = DockStyle.Fill; pb.Parent = sc.Panel2; pb.BackColor = Color.LightBlue;
        sc.Size = new Size(this.Width, this.Height-flp.Height);
        sc.Location = new Point(0, flp.Height);
        sc.Anchor = AnchorStyles.Left | AnchorStyles.Right | AnchorStyles.Bottom;
        this.Controls.Add(sc);

这是解决方案。感谢@Fabio。

        this.Size = new Size(300, 400);

        TableLayoutPanel tlp = new TableLayoutPanel();
        tlp.RowCount = 2;
        tlp.ColumnCount = 1;
        tlp.Dock = DockStyle.Fill;
        this.Controls.Add(tlp);            

        string[] tags = new string[] { "action", "romance", "drama", "sci-fi", "horror" };
        FlowLayoutPanel flp = new FlowLayoutPanel();
        flp.AutoSize = true;
        flp.Dock = DockStyle.Fill;
        flp.BackColor = Color.LightCyan;
        flp.FlowDirection = FlowDirection.LeftToRight;
        tlp.Controls.Add(flp, 0, 0);

        foreach (string tag in tags)
        {
            Button btn = new Button();
            btn.Text = tag;
            flp.Controls.Add(btn);
        }

        SplitContainer sc = new SplitContainer();
        ListBox lb = new ListBox(); lb.Dock = DockStyle.Fill; lb.Parent = sc.Panel1; lb.Items.Add("test");
        PictureBox pb = new PictureBox(); pb.Dock = DockStyle.Fill; pb.Parent = sc.Panel2; pb.BackColor = Color.LightBlue;
        sc.Dock = DockStyle.Fill;
        tlp.Controls.Add(sc,0,1);

0 个答案:

没有答案