2
我正在使用PropertyGrid
控件編輯我的類屬性,我試圖根據其他屬性設置將某些屬性設置爲只讀。在PropertyGrid中設置ReadOnly屬性將所有屬性設置爲只讀
這是我的類的代碼:
Imports System.ComponentModel
Imports System.Reflection
Public Class PropertyClass
Private _someProperty As Boolean = False
<DefaultValue(False)>
Public Property SomeProperty As Boolean
Get
Return _someProperty
End Get
Set(value As Boolean)
_someProperty = value
If value Then
SetReadOnlyProperty("SerialPortNum", True)
SetReadOnlyProperty("IPAddress", False)
Else
SetReadOnlyProperty("SerialPortNum", False)
SetReadOnlyProperty("IPAddress", True)
End If
End Set
End Property
Public Property IPAddress As String = "0.0.0.0"
Public Property SerialPortNum As Integer = 0
Private Sub SetReadOnlyProperty(ByVal propertyName As String, ByVal readOnlyValue As Boolean)
Dim descriptor As PropertyDescriptor = TypeDescriptor.GetProperties(Me.GetType)(propertyName)
Dim attrib As ReadOnlyAttribute = CType(descriptor.Attributes(GetType(ReadOnlyAttribute)), ReadOnlyAttribute)
Dim isReadOnly As FieldInfo = attrib.GetType.GetField("isReadOnly", (BindingFlags.NonPublic Or BindingFlags.Instance))
isReadOnly.SetValue(attrib, readOnlyValue)
End Sub
End Class
這是我使用編輯值碼:
Dim c As New PropertyClass
PropertyGrid1.SelectedObject = c
的問題是,當我設置SomeProperty
到True
,沒什麼發生時,然後當我再次將其設置爲False
時,它會設置全部屬性只讀。有人可以在我的代碼中看到錯誤嗎?
輝煌 - 謝謝拉爾斯 –