如何以编程方式复制自定义控件(面板)

时间:2013-09-20 17:20:09

标签: winforms custom-controls custom-component

我在VS 2010中使用C#。我创建了一个自定义面板,并希望将此自定义面板添加9次,因此我创建了一个循环,以相互相等的距离添加9次面板副本。每个面板都有自己的文本和图像。我所能得到的只是一个小组。任何见解都将不胜感激

public partial class Form1 : Form
{
    int index = 0;
    List<CutePanel.CustomPanel> MenuItems = new List<CutePanel.CustomPanel>(); 
    public Form1()
    {
        InitializeComponent();

        for (int i = 0; i < 9; i++)
        {
            this.cpTest.BackColor = System.Drawing.SystemColors.ActiveCaption;
            this.cpTest.LabelText = "My super click text";
            this.cpTest.Location = new System.Drawing.Point(12, 12+(64*i));
            this.cpTest.Name = "cpTest";
            this.cpTest.Size = new System.Drawing.Size(344, 58);
            this.cpTest.SuperClick = null;
            this.cpTest.TabIndex = 6;
        }

        cpTest.MouseClick += new MouseEventHandler(cpTest_MouseClick);
        cpTest.SuperClick += new EventHandler(cpTest_SuperClick);
        cpTest.LabelText = "This is my text.";
        MenuItems.Add(cpTest);

    }

    void cpTest_SuperClick(object sender, EventArgs e)
    {
        tcTest.SelectedIndex = index++ % 2;
    }

    void cpTest_MouseClick(object sender, MouseEventArgs e)
    {
        tcTest.SelectedIndex = index++ % 2;
    }

    private void customPanel3_MouseClick(object sender, MouseEventArgs e)
    {
        tcTest.SelectedIndex = index++ % 2;
    }



} 

感谢。

1 个答案:

答案 0 :(得分:0)

您必须区分面板类和面板对象,也称为此类的实例。将类视为用于创建对象的模板。这些对象是使用new关键字创建的:

for (int i = 0; i < 9; i++)
{
    var cp = new CutePanel.CustomPanel();
    cp.BackColor = System.Drawing.SystemColors.ActiveCaption;
    cp.LabelText = "My super click text";
    cp.Location = new System.Drawing.Point(12, 12+(64*i));
    cp.Name = "cpTest" + i;
    cp.Size = new System.Drawing.Size(344, 58);
    cp.SuperClick = null;
    cp.TabIndex = 6;

    cp.MouseClick += new MouseEventHandler(cpTest_MouseClick);
    cp.SuperClick += new EventHandler(cpTest_SuperClick);

    cp.LabelText = "This is my text.";
    MenuItems.Add(cp);
}

您也可以从现有面板中为其指定值:

cp.BackColor = cpTest.BackColor;
cp.Size = cpTest.Size;
...

制作副本的优雅方法是在面板类中包含Clone方法

public class CustomPanel
{
    ...

    public CustomPanel Clone()
    {
        var cp = (CustomPanel)this.MemberwiseClone();
        cp.Parent = null; // It has not yet been added to the form.
        return cp;
    }
}

然后

for (int i = 0; i < 9; i++)
{
    CustomPanel cp = cpTest.Clone();

    // Now only change the differing properties
    cp.Location = new System.Drawing.Point(12, 12+(64*i));
    cp.Name = "cpTest" + i;
    cp.TabIndex += i + 1;

    MenuItems.Add(cp);
}

但注意:如果克隆的控件是包含其他控件的容器控件,则还必须以递归方式克隆这些控件。即,你必须进行深度克隆!如我的第一个代码段所示创建新控件更安全。