Create custom winforms container

时光毁灭记忆、已成空白 提交于 2019-12-03 01:49:33
Henry Rodriguez

Maybe this is what you need, I found it at CodeProject a time ago:

Designing Nested Controls:

This article demonstrates how to allow a Control, which is a child of another Control to accept having controls dropped onto it at design time. It is not a large article, there is not much by way of code, and this may not be either the 'official' or best way to do this. It does, however, work, and is stable as far as I have been able to test it.

You need to add a Designer attribute to your control, and use a type that derives from or is the ParentControlDesigner Class (needs a reference to the System.Design.dll assembly), like this:

[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;
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!