在PropertyGrid中设置只读属性设置所有属性只读(Setting ReadOnly Prop

2019-09-18 00:49发布

我使用的是PropertyGrid控制编辑我的类属性,我想设置某些属性只读依赖于其他属性设置。

这是我的类的代码:

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

问题是,当我设置SomePropertyTrue ,没有任何反应,当我然后将其设置为False它再次设置只读的所有属性。 有人可以看到我的代码中的错误?

Answer 1:

尝试装饰全部用你的类属性的ReadOnly属性:

<[ReadOnly](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

<[ReadOnly](False)> _
Public Property IPAddress As String = "0.0.0.0"

<[ReadOnly](False)> _
Public Property SerialPortNum As Integer = 0

发现从这个代码项目: 启用/ PropertyGrid中的在运行时禁用特性

为了让这一切都正常工作,但静态定义类任何你想要的价值的每个属性的只读属性是很重要的。 如果不是,在运行时更改的属性,这样会错误地修改类的每个属性的属性。



文章来源: Setting ReadOnly Property in PropertyGrid Sets All Properties Readonly