0

我正在对现有应用程序进行更改。我被困在一个需要在流面板中间添加控件的问题上。我已经简化了下面的问题。

每个对象添加一个标签和按钮控件。我在初始屏幕启动时添加了 3 组对象。

在此处输入图像描述

当用户单击任何按钮时,会添加另一个对象:

在此处输入图像描述

但是,我需要控件位于单击它的按钮下方,而不是添加到底部。例如,单击 A 按钮,然后标签 D 和按钮 d 应出现在 A 按钮下方并向下移动其他控件。该事件是一个按钮,但也可以是其他事件,例如下拉菜单,但规则/行为是相同的。是否可以在流面板中间添加控件?

以下是代码示例:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApp8
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            List<Control_Info> list = new List<Control_Info>();
            list.Add(new Control_Info { Label_Name = "Test A", Button_Name = "Desc A" });
            list.Add(new Control_Info { Label_Name = "Test B", Button_Name = "Desc B" });
            list.Add(new Control_Info { Label_Name = "Test C", Button_Name = "Desc C" });

            foreach (Control_Info ci in list)
            {
                loadControlToPanel(ci);
            }

        }

        private void loadControlToPanel(Control_Info ci)
        {
            Label label = new Label();
            label.Text = ci.Label_Name;
            label.AutoSize = false;
            flowLayoutPanel1.Controls.Add(label);

            Button button = new Button();
            button.Text = ci.Button_Name;
            button.AutoSize = false;
            button.Click += new EventHandler(buttonClickEvent);
            flowLayoutPanel1.Controls.Add(button);
        }

        private void buttonClickEvent(object sender, EventArgs e)
        {
            Control_Info ci = new Control_Info{ Label_Name = "Test D", Button_Name = "Desc D" };
            loadControlToPanel(ci);
        }
    }
}
4

1 回答 1

1

使用SetChildIndex(...);方法,例如:

    Form f5 = new Form();
    FlowLayoutPanel panel = new FlowLayoutPanel { FlowDirection = FlowDirection.TopDown, Dock = DockStyle.Fill };
    f5.Controls.Add(panel);
    Label lbA = new Label { Text = "A" };
    Button btnA = new Button { Text = "A" };
    panel.Controls.Add(lbA);
    panel.Controls.Add(btnA);
    char c = 'B';
    EventHandler action = null; 
    action = (o, e) => {
        int index = panel.Controls.IndexOf((Control) o); // index of button clicked
        Label lbNew = new Label { Text = c.ToString() };
        Button btnNew = new Button { Text = c.ToString() };
        btnNew.Click += action;
        c++;
        panel.SuspendLayout();
        panel.Controls.Add(lbNew);
        panel.Controls.Add(btnNew);
        panel.Controls.SetChildIndex(btnNew, index+1);
        panel.Controls.SetChildIndex(lbNew, index+1);   
        panel.ResumeLayout(true);
    };
    btnA.Click += action;

    Application.Run(f5);
于 2021-06-10T22:53:00.900 回答