创建自定义winforms容器

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

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

但我无法弄清楚如何让我的控件在设计模式中对这种动作做出反应。

也许这就是你需要的,我在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; } }