如何在运行时间在c#中添加自定义控件

How to add custom control at Run time in c#

我有一个列表框,它有按钮、文本框、标签。在运行时,我将从列表框中拖放项目,根据 selection 将创建动态控件。 (例如,如果我 select 并将按钮从列表框中拖放到 Windows 表单上,将创建按钮)。与我为 Button 创建 CustomControl 一样。我如何在运行时将它添加到我的列表框中?我的意思是当我从列表框中拖放按钮时,应该生成自定义按钮。怎么做?

你试过吗?

var list = new ListBox();
list.Controls.Add(new Button());

如果您需要在运行时动态创建 class - 请查看这篇 SF 文章 How to dynamically create a class in C#?

对于拖放,您需要设置 3 个事件:

  1. 列表框上的鼠标按下事件触发拖动:

    private void listBox1_MouseDown(object sender, MouseEventArgs e)
    {
        listBox1.DoDragDrop(listBox1.SelectedItem, DragDropEffects.Copy);
    }
    
  2. 表单(或本例中的面板)上的拖动输入事件:

    private void panel1_DragEnter(object sender, DragEventArgs e)
    {
        if (e.Data.GetDataPresent(DataFormats.Text))
        {
            e.Effect = DragDropEffects.Copy;
        }
    }
    
  3. 最后是 form/panel 上的掉落事件:

    private void panel1_DragDrop(object sender, DragEventArgs e)
    {
        Control newControl = null;
        // you would really use a better design pattern to do this, but
        // for demo purposes I'm using a switch statement
        string selectedItem = e.Data.GetData(DataFormats.Text) as string;
        switch (selectedItem)
        {
            case "My Custom Control":
                newControl = new CustomControl();
                newControl.Location = panel1.PointToClient(new Point(e.X, e.Y));
                newControl.Size = new System.Drawing.Size(75, 23);
                break;
        }
    
        if (newControl != null) panel1.Controls.Add(newControl);
    }
    

为此,您必须在目标 form/panel 上将 "AllowDrop" 设置为 true。

使用@Marty 的回答将自定义控件添加到列表框。覆盖 ToString() 以获得更好的描述。有很多方法可以做到这一点。重要的部分是决定列表项的数据类型,并确保在 e.Data.GetDataPresent 方法中使用正确的类型名称。 e.Data.GetFormats() 可以帮助确定要使用的名称。