如何动态复制控制面板?

问题描述 投票:0回答:1

我想根据整数复制与其他面板相同样式的面板。

例如

Integer = 3

所以我有原始面板并使用 C# 以相同的样式复制了三遍

c# winforms duplicates panel
1个回答
0
投票

您可以使用

PropertyInfo[]
在 WinForms 中克隆控件。
这里有一个复制面板控制的方法:

private Panel GetClonedPanel(Panel panel)
{
    PropertyInfo[] controlProperties = typeof(Panel).GetProperties(BindingFlags.Public | BindingFlags.Instance);

    Panel cloned = Activator.CreateInstance<Panel>();

    foreach (PropertyInfo propInfo in controlProperties)
    {
        if (propInfo.CanWrite)
        {
            if (propInfo.Name != "WindowTarget")
                propInfo.SetValue(cloned, propInfo.GetValue(panel, null), null);
        }
    }

    return cloned;
}

实施:

private void button1_Click(object sender, EventArgs e)
{
    int inTeger = 3;
    int x = panel1.Location.X;
    for (int i = 0; i <= inTeger; i++)
    {
        // Clone the control
        Panel cloned = GetClonedPanel(panel1);
        x = x + cloned.Width + 2;
        // Add it to the form
        cloned.Location = new Point(x, panel1.Location.Y);
        this.Controls.Add(cloned);
    }
}

输出:

© www.soinside.com 2019 - 2024. All rights reserved.