如何克隆“模板”标签页C#

时间:2015-12-07 17:37:32

标签: c# clone tabcontrol tabpage

所以我的标签控件中有一个模板标签页,其中包含一个多行文本框,一个按钮,一个进度条和一个标签。我试图搜索克隆模板标签页并将其添加到我的标签控件,但由于某种原因,它在某个时刻崩溃了大约一半。是否导致标签页内部有控件?我应该克隆每个控件然后将它们添加到新创建的标签页吗?是否更容易创建这些控件并只在运行时设置值?我想我一定是做错了,因为我很难找到关于这样做的信息。

private void copyControl(Control sourceControl, Control targetControl)
    {
        // make sure these are the same
        if (sourceControl.GetType() != targetControl.GetType())
        {
            throw new Exception("Incorrect control types");
        }

        foreach (PropertyInfo sourceProperty in sourceControl.GetType().GetProperties())
        {
            object newValue = sourceProperty.GetValue(sourceControl, null);

            MethodInfo mi = sourceProperty.GetSetMethod(true);
            if (mi != null)
            {
                sourceProperty.SetValue(targetControl, newValue, null);
            }
        }
    }

附带问题,这似乎可能有名称重叠,或者这不重要,因为每个控件都属于不同的标签页?

1 个答案:

答案 0 :(得分:0)

您要使用此解决方案遇到的第一个问题是您正在复制控件ID,这会在父控件中产生冲突"&#34 ;控制与#34;集合。

此外,当您致电" GetProperties()"你应该使用BindingFlags枚举来确保你只获取具有" Set"的公共属性。访问。然后,您可以删除" GetSetMethod()"。

的额外调用
    private void copyControl(Control sourceControl, Control targetControl)
    {
        // make sure these are the same
        if (sourceControl.GetType() != targetControl.GetType())
        {
            throw new Exception("Incorrect control types");
        }

        foreach (PropertyInfo sourceProperty in sourceControl.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.SetProperty))
        {
            object newValue = sourceProperty.GetValue(sourceControl, null);
            sourceProperty.SetValue(targetControl, newValue, null);
        }
    }