I am using a PropertyGrid
control to edit my class properties and I am trying to set certain properties read-only depending on other property settings.
This is the code of my class:
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
This is the code I am using to edit the values:
Dim c As New PropertyClass
PropertyGrid1.SelectedObject = c
The problem is that when I set SomeProperty
to True
, nothing happens and when I then set it to False
again it sets all properties Read-Only. Can someone see an error in my code?
Try decorating ALL of your class properties with the
ReadOnly
attribute:Found it from this Code Project: Enabling/disabling properties at runtime in the PropertyGrid