尝试创建自定义面板

时间:2019-11-19 00:17:07

标签: c# custom-panel

我正在尝试创建一个自定义面板,其中将包含许多控件。这是我第一次创建这样的自定义控件。此示例包含一个面板,该面板内部带有按钮。

我不确定为什么单击按钮时面板没有添加到Form1中。
我在代码中丢失了什么吗?

        private void button2_Click(object sender, EventArgs e)
        {
            streamingPanel sp = new streamingPanel();
            sp.Size = new Size(319, 240);
            Point point = new Point(50, 50);
            sp.Location = point;
            this.Controls.Add(sp);
        }
        public class streamingPanel : Panel
        {
            public System.Windows.Forms.Panel panel1;
            public System.Windows.Forms.Button button1;

            public streamingPanel()
            {
                InitializeComponent();
            }

            private void InitializeComponent()
            {
                this.panel1 = new System.Windows.Forms.Panel();
                this.button1 = new System.Windows.Forms.Button();
                this.panel1.SuspendLayout();
                // 
                // panel1
                // 
                this.panel1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
                this.panel1.Controls.Add(this.button1);
                this.panel1.Location = new System.Drawing.Point(483, 91);
                this.panel1.Name = "panel1";
                this.panel1.Size = new System.Drawing.Size(319, 240);
                this.panel1.TabIndex = 0;
                // 
                // button1
                // 
                this.button1.Location = new System.Drawing.Point(100, 72);
                this.button1.Name = "button1";
                this.button1.Size = new System.Drawing.Size(75, 23);
                this.button1.TabIndex = 0;
                this.button1.Text = "button1";
                this.button1.UseVisualStyleBackColor = true;
            }
        }

1 个答案:

答案 0 :(得分:1)

在将控件添加到窗体时,观察Visual Studio编辑器的作用。代码在表单的构造函数中调用的方法InitializeComponent中。例如,您忘记设置新控件的LocationSize