【问题标题】:Setting ReadOnly Property in PropertyGrid Sets All Properties Readonly在 PropertyGrid 中设置 ReadOnly 属性将所有属性设置为只读
【发布时间】:2012-06-12 08:08:12
【问题描述】:

我正在使用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

问题是,当我将 SomeProperty 设置为 True 时,什么也没有发生,当我再次将其设置为 False 时,它会将 all 属性设置为只读。有人能在我的代码中看到错误吗?

【问题讨论】:

    标签: .net vb.net reflection attributes propertygrid


    【解决方案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
    

    从这个代码项目中找到它:Enabling/disabling properties at runtime in the PropertyGrid

    为了使这一切正常工作,重要的是静态地将类的每个属性的 ReadOnly 属性定义为您想要的任何值。如果不是这样,那么在运行时更改属性会错误地修改类的每个属性的属性。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-12-05
      • 2013-02-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多