0

我在重绘克隆面板的子控件时遇到问题。

首先,我没有使用 IClonable。我正在使用反射

我的代码:

public static Panel ClonePanel(Panel panel)
{
    Panel newPanel = (Panel) CloneControl(panel);

    foreach (Control ctl in panel.Controls)
    {
        Control newCtl = CloneControl(ctl);
        newCtl.Visible = true;

        newPanel.Controls.Add(newCtl);
    }

    newPanel.Visible = true;

    return newPanel;
}

public static Control CloneControl(Control o)
{
    Type type = o.GetType();
    PropertyInfo[] properties = type.GetProperties();
    Control retObject = (Control) type.InvokeMember("", System.Reflection.BindingFlags.CreateInstance, null, o, null);
    foreach (PropertyInfo propertyInfo in properties)
    {
        if (propertyInfo.CanWrite)
        {
            propertyInfo.SetValue(retObject, propertyInfo.GetValue(o, null), null);
        }
    }
    return retObject;
}
4

2 回答 2

1

对于第二个问题,添加对 System.Design 的引用。然后将 [Deisgner(typeof( ParentControlDesigner )] 属性添加到您的用户控件。这将让它在设计时像面板控件一样工作。

于 2009-12-01T05:40:24.750 回答
-1

因此,我通过使用 UserControl 而不是 Panel 解决了这个问题,结果证明效果要好得多。

我唯一想要另外的是,不仅在其特定的设计器中设计 UserControl 控件,而且在 Form 本身中设计。但这不是问题,我可以忍受。

于 2009-11-22T10:04:14.120 回答