我有Windows表单,让我们说TextBox1
和Button1
。点击Button1
后,会在初始TextBox2
下方创建新的TextBox1
。如何将所有属性从TextBox1
导入TextBox2
,以便它们看起来完全相同(大小,文字,背景颜色,字体等)?
答案 0 :(得分:0)
您可以使用反射来克隆文本框(抱歉C#):
private void button1_Click(object sender, EventArgs e)
{
TextBox t = (TextBox)CloneObject(textBox1);
}
private object CloneObject(object o)
{
Type t = o.GetType();
PropertyInfo[] properties = t.GetProperties();
Object p = t.InvokeMember("", System.Reflection.BindingFlags.CreateInstance, null, o, null);
foreach(PropertyInfo pi in properties)
{
if(pi.CanWrite)
{
pi.SetValue(p, pi.GetValue(o, null), null);
}
}
return p;
}
答案 1 :(得分:0)
非常感谢Fabian Bigler的C#代码。这是VB.net的等价物:
Private Function CloneControl(ByVal control As Object) As Object
Dim type As Type = control.GetType()
Dim properties As PropertyInfo() = type.GetProperties()
Dim retObject As Object = type.InvokeMember("", System.Reflection.BindingFlags.CreateInstance, Nothing, control, Nothing)
For Each p As PropertyInfo In properties
If p.CanWrite Then
p.SetValue(retObject, p.GetValue(control, Nothing), Nothing)
End If
Next
Return retObject
End Function
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Combobox3 = DirectCast(CloneControl(ComboBox2), ComboBox)
End Sub