创建自定义winforms容器

本文关键字:容器 winforms 自定义 创建 | 更新日期: 2023-09-27 18:15:16

我想在winforms中创建一个与容器控件具有相同行为的控件。我的意思是:在设计模式下,当我将控件放入其中时,它会将它们分组,就像分组框一样。

我正在创建的这个控件包含一些其他控件和一个组框。我所需要的是:当一个控件在设计模式下被拖放到我的自定义控件上时,我将把它放在嵌套的GroupBox中。

但是我不知道如何让我的控件在设计模式下响应这种动作

创建自定义winforms容器

也许这是你需要的,我发现它在CodeProject前一段时间:

设计嵌套控件:

本文演示如何允许控件,它是控件的子控件另一个控件接受在设计时将控件放到其上时间。这不是一篇大文章,没有太多的代码,而且这可能不是"官方的"或最好的方法。是这样,然而,工作,并且是稳定的,就我所能测试它。

您需要为控件添加一个Designer属性,并使用派生自ParentControlDesigner类的类型(需要对System.Design.dll程序集的引用),如下所示:

[Designer(typeof(MyCustomControlDesigner1))]
public partial class CustomControl1 : Control
{
    public CustomControl1()
    {
        MyBox = new GroupBox();
        InitializeComponent();
        MyBox.Text = "hello world";
        Controls.Add(MyBox);
    }
    public GroupBox MyBox { get; private set; }
}
public class MyCustomControlDesigner1 : ParentControlDesigner
{
    // When a control is parented, tell the parent is the GroupBox, not the control itself
    protected override Control GetParentForComponent(IComponent component)
    {
        CustomControl1 cc = (CustomControl1)Control;
        return cc.MyBox;
    }
}