0

我在 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;
    }



} 

谢谢。

4

1 回答 1

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

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

于 2013-09-20T17:38:19.040 回答