Create custom winforms container

后端 未结 2 805
甜味超标
甜味超标 2021-02-05 10:25

I want to create a control in winforms with same behavior as the container controls. I mean: in design mode, when I drop controls in it, it will group then, just like a groupbox

2条回答
  •  醉话见心
    2021-02-05 10:54

    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;
        }
    }
    

提交回复
热议问题