在流布局面板中的按钮下添加标签

本文关键字:按钮 添加 加标签 流布局 | 更新日期: 2023-09-27 17:55:54

当我将文件拖放到表单上时,我需要在flowLayoutPanel中动态创建带有标签的按钮。但是我如何将标签位置设置为按钮下方,因为 FLP 会自行排列控件。?

我尝试过:

 void Form1_DragDrop(object sender, DragEventArgs e)
    {
        string[] fileList = e.Data.GetData(DataFormats.FileDrop) as string[];
        foreach (string s in fileList)
            {
                Button button = new Button();
                button.Click += new EventHandler(this.button_Click);
                fl_panel.Controls.Add(button);
                Icon icon = System.Drawing.Icon.ExtractAssociatedIcon(filename);
                Bitmap bmp = icon.ToBitmap();
                button.BackgroundImage = bmp;
                button.Width = 60;
                button.Height = 75;
                button.FlatStyle = FlatStyle.Flat;
                button.BackgroundImageLayout = ImageLayout.Stretch;            
                int space = 5;
                int Yy = button.Location.Y;
                int Xx = button.Location.X;
            Label label = new Label();
            label.Location = new Point(Yy + space, Xx);
            //label.Margin.Top = button.Margin.Bottom;
            fl_panel.Controls.Add(label);
            }
    }

在流布局面板中的按钮下添加标签

我知道的最好的主意是实现一个自定义控件,其中包含正确排列的按钮和标签。 然后将自定义控件添加到 FlowLayoutPanel。

public class CustomControl:Control
{
    private Button _button;
    private Label _label;
    public CustomControl(Button button, Label label)
    {
        _button = button;
        _label = label;
        Height = button.Height + label.Height;
        Width = Math.Max(button.Width, label.Width);
        Controls.Add(_button);
        _button.Location = new Point(0,0);
        Controls.Add(_label);
        _label.Location = new Point(0, button.Height);
    }
}

然后,您可以像这样添加它:

for (int i = 0; i < 10; i++)
{
    CustomControl c = new CustomControl(new Button {Text = "Button!"}, new Label {Text = "Label!"});
    fl_panel.Controls.Add(c);
}

编辑:如果要收听按钮事件,请尝试以下操作:

for (int i = 0; i < 10; i++)
{
    var button = new Button {Text = "Button " + i};
    CustomControl c = new CustomControl(button, new Label {Text = "Label!"});
    button.Click += buttonClicked;
    fl_panel.Controls.Add(c);
}
...
private void buttonClicked(object sender, EventArgs e)
{
    MessageBox.Show(((Button) sender).Text);
}