克隆控件 - C# (Winform)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10266589/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 13:05:40  来源:igfitidea点击:

Clone Controls - C# (Winform)

c#winforms

提问by Farid-ur-Rahman

Possible Duplicate:
It is possible to copy all the properties of a certain control? (C# window forms)

可能的重复:
是否可以复制某个控件的所有属性?(C# 窗体)

I have to create some controls similar to a control created as design time. The created control should have same properties as a predefined control, or in other words I want to copy a control. Is there any single line of code for that purpose? or I have to set each property by a line of code? I am doing right now is:

我必须创建一些类似于在设计时创建的控件的控件。创建的控件应该与预定义的控件具有相同的属性,或者换句话说,我想复制一个控件。是否有任何一行代码用于此目的?或者我必须通过一行代码设置每个属性?我现在正在做的是:

        ListContainer_Category3 = new FlowLayoutPanel();
        ListContainer_Category3.Location = ListContainer_Category1.Location;
        ListContainer_Category3.BackColor = ListContainer_Category1.BackColor;
        ListContainer_Category3.Size = ListContainer_Category1.Size;
        ListContainer_Category3.AutoScroll = ListContainer_Category1.AutoScroll;

回答by Marcel Roma

Generally speaking you can use reflection to copy the public properties of an object to a new instance.

一般来说,您可以使用反射将对象的公共属性复制到新实例。

When dealing with Controls however, you need to be cautious. Some properties, like WindowTarget are meant to be used only by the framework infrastructure; so you need to filter them out.

但是,在处理控件时,您需要谨慎。某些属性,例如 WindowTarget 只能由框架基础结构使用;所以你需要过滤掉它们。

After filtering work is done, you can write the desired one-liner:

过滤工作完成后,就可以写出想要的单行了:

Button button2 = button1.Clone();

Here's a little code to get you started:

这里有一些代码可以帮助您入门:

public static class ControlExtensions
{
    public static T Clone<T>(this T controlToClone) 
        where T : Control
    {
        PropertyInfo[] controlProperties = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);

        T instance = Activator.CreateInstance<T>();

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

        return instance;
    }
}

Of course, you still need to adjust naming, location etc. Also maybe handle contained controls.

当然,你仍然需要调整命名、位置等。也可能处理包含的控件。