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

时间:2009-08-31 09:39:22

标签: c# winforms user-controls

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

当我在设计器中拖动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);
    }
}

2 个答案:

答案 0 :(得分:8)

看看这里

How to make a UserControl object acts as a control container design-time by using Visual C#

但是如果你只需要扩展的Panel功能,最好直接从Panel继承。

答案 1 :(得分:2)

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

[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");

    }

}

(其他来源:Add Control to UserControl