在flowLayoutPanel中的按钮下添加标签

时间:2014-04-01 08:08:55

标签: c# button label flowlayoutpanel

当我将文件拖放到表单上时,我需要在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);
            }
    }

1 个答案:

答案 0 :(得分:1)

我所知道的最好的想法是实现一个自定义控件,其中包含正确排列的按钮和标签。然后将自定义控件添加到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);
}