如何用反射查找控件属性
在winform 中有一个listview控件,名为listview1
1.取listview1.columns(0).width值
2.设置listview1.columns(0).width值
能用以下方法修改一下最好.
Public Function GetValueControlProperty(ByVal ClassInstance As Object, ByVal ControlName As String, ByVal PropertyName As String) As Object
Dim Result As Object = Nothing
Dim myType As Type = ClassInstance.GetType
Dim myFieldInfo As FieldInfo = myType.GetField( "_ " & ControlName, BindingFlags.NonPublic Or BindingFlags.Instance Or BindingFlags.Public Or BindingFlags.GetField Or BindingFlags.GetProperty Or BindingFlags.SetField Or BindingFlags.Static Or BindingFlags.Default)
If Not myFieldInfo Is Nothing Then
Dim properties As PropertyDescriptorCollection = TypeDescriptor.GetProperties(myType)
Dim myProperty As PropertyDescriptor = properties.Find(PropertyName, True)
'End If
If Not myProperty Is Nothing Then
Dim ctr As Object
ctr = myFieldInfo.GetValue(ClassInstance)
Try
Result = myProperty.GetValue(ctr)
Catch ex As Exception
MsgBox(ex.Message)
End Try
End If
End If
Return Result
End Function
Public Function SetValueControlProperty(ByVal ClassInstance As Object, ByVal ControlName As String, ByVal PropertyName As String, ByVal Value As Object) As Object
Dim Result As Object = Nothing
Dim myType As Type = ClassInstance.GetType
Dim myFieldInfo As FieldInfo = myType.GetField( "_ " & ControlName, BindingFlags.NonPublic Or BindingFlags.Instance Or BindingFlags.Public Or BindingFlags.Instance) '加 "_ "这个是特要紧的
If Not myFieldInfo Is Nothing Then
Dim properties As PropertyDescriptorCollection = TypeDescriptor.GetProperties(myType)
Dim myProperty As PropertyDescriptor = properties.Find(PropertyName, True) '这里设为True就不用区分大小写了
If Not myProperty Is Nothing Then
Dim ctr As Object
ctr = myFieldInfo.GetValue(ClassInstance) '取得控件实例
Try
myProperty.SetValue(ctr, Value)
Result = ctr
Catch ex As Exception
MsgBox(ex.Message)
End Try
End If
End If
Return Result
End Function
[解决办法]
这样看看:
1.取listview1.columns(0).width值 GetValueControlProperty(listview1.columns(0), "ColumnHeader ", "Width ")
2.设置listview1.columns(0).width值 SetValueControlProperty(listview1.columns(0), "ColumnHeader ", "Width ", "250 ")