C#用户控件作为自定义面板

我创建自己的用户控件,只包含一个面板:

当我在设计器中拖动myPanel对象然后尝试在其上添加按钮时,该按钮实际上被添加到窗体的控件中。

我必须设置一个属性/属性才能执行此操作,另一种方法可以执行我想要的操作吗?

public class MyPanel : UserControl { private Panel panelMain; public MyPanel() { InitializeComponent(); } private void InitializeComponent() { this.panelMain = new System.Windows.Forms.Panel(); this.SuspendLayout(); // // panelMain // this.panelMain.BackColor = System.Drawing.SystemColors.ActiveCaption; this.panelMain.Dock = System.Windows.Forms.DockStyle.Fill; this.panelMain.Location = new System.Drawing.Point(0, 0); this.panelMain.Name = "panelMain"; this.panelMain.Size = new System.Drawing.Size(150, 150); this.panelMain.TabIndex = 0; // // myPanel // this.Controls.Add(this.panelMain); this.Name = "MyPanel"; this.ResumeLayout(false); } } 

看看这里

如何通过使用Visual C#使UserControl对象充当控件容器设计时

但是如果你只需要扩展的Panelfunction,那么最好直接从Panelinheritance。

更确切地说,我做了以下事情:

 [Designer(typeof(myControlDesigner))] public class MyPanel : UserControl { private TableLayoutPanel tableLayoutPanel1; private Panel panelMain; ... [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] public Panel InnerPanel { get { return panelMain; } set { panelMain = value; } } [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] public TableLayoutPanel InnerTableLayout { get { return tableLayoutPanel1; } set { tableLayoutPanel1 = value; } } } 

使用[Designer(typeof(myControlDesigner))的myControlDesigner]

 class myControlDesigner : ParentControlDesigner { public override void Initialize(IComponent component) { base.Initialize(component); MyPanel myPanel = component as MyPanel; this.EnableDesignMode(myPanel.InnerPanel, "InnerPanel"); this.EnableDesignMode(myPanel.InnerTableLayout, "InnerTableLayout"); } } 

(其他来源: 将控件添加到UserControl )