克隆控件 - C# (Winform) [英] Clone Controls - C# (Winform)
问题描述
可能的重复:
它是可以复制某个控件的所有属性吗?(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;
推荐答案
一般来说,您可以使用反射将对象的公共属性复制到新实例中.
Generally speaking you can use reflection to copy the public properties of an object to a new instance.
然而,在处理控件时,您需要谨慎.一些属性,如 WindowTarget 只能由框架基础设施使用;所以你需要过滤掉它们.
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.
过滤工作完成后,就可以写出想要的单行了:
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.
这篇关于克隆控件 - C# (Winform)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!