代码之家  ›  专栏  ›  技术社区  ›  Toto

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

  •  8
  • Toto  · 技术社区  · 15 年前

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

    当我在设计器中拖动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 回复  |  直到 9 年前
        1
  •  8
  •   Attacktive    9 年前

    看看这里

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

    但如果您只需要扩展面板功能,最好直接从面板继承。

        2
  •  2
  •   Toto    15 年前

    更准确地说,我做了以下工作:

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

    对于[设计器(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 )