'按控件实例名称及其属性名称实现动态赋值
'入口参数:ClassInstance 控件所在的类实例
' ControlName 控件实例名称,区分大小写
' PropertyName 要设值的控件属性名称,区分大小写(其实这里可以不必区分大小写的,只是为了养成习惯,我这样要求自己的)
' Value 新值,类型是一个Object,这倒是要注意的
'出口参数: True则重设成功,False不成功
'需要 Imports System.Reflection和Imports System.ComponentModel
Public Function SetValueControlProperty(ByVal ClassInstance As Object, ByVal ControlName As String, ByVal PropertyName As String, ByVal Value As Object) As Boolean
Dim Result As Boolean = False '返回值。虽然默认是Flase,但我还是喜欢这样设它,主要是看着明了
'下面我不注释了
Dim myType As Type = ClassInstance.GetType
Dim myFieldInfo As FieldInfo = myType.GetField("_" & ControlName, BindingFlags.NonPublic Or _
BindingFlags.Instance Or BindingFlags.Public) '加"_"这个是特要紧的
If Not myFieldInfo Is Nothing Then
Dim properties As PropertyDescriptorCollection = TypeDescriptor.GetProperties(myType)
Dim myProperty As PropertyDescriptor = properties.Find(PropertyName, False) '这里设为True就不用区分大小写了
If Not myProperty Is Nothing Then
Dim ctr As Object
ctr = myFieldInfo.GetValue(ClassInstance) '取得控件实例
Try
myProperty.SetValue(ctr, Value)
Result = True
Catch ex As Exception
MsgBox(ex.Message)
End Try
End If
End If
Return Result
End Function
'测试
Private Sub Test()
SetValueControlProperty(Me, "Button1", "Text", "Hello")
SetValueControlProperty(Me, "Button2", "Visible", False)
Dim frm As New Form2
SetValueControlProperty(frm, "MyTextBox", "Text", "应该还行吧?")
frm.Show()
End Sub