.net - 在 PropertyGrid 中设置只读属性将所有属性设置为只读

标签 .net vb.net reflection attributes propertygrid

我正在使用 PropertyGrid 控件来编辑我的类属性,并且我尝试根据其他属性设置将某些属性设置为只读。

这是我类(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

这是我用来编辑值的代码:

    Dim c As New PropertyClass
    PropertyGrid1.SelectedObject = c

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

最佳答案

尝试使用 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

In order for all this to work properly, it is important to statically define the ReadOnly attribute of every property of the class to whatever value you want. If not, changing the attribute at runtime that way will wrongly modify the attributes of every property of the class.

关于.net - 在 PropertyGrid 中设置只读属性将所有属性设置为只读,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10992719/

相关文章:

c# - .NET 中最精确的计时器是什么?

vb.net - 使用 .Split 删除空条目

.net - 在 SQL Server 表中存储证书文件

c# - 无法以不同用户身份运行 C# 进程

c# - 从异步方法立即抛出

mysql - 如何从类中调用模块?

vb.net - 为什么 Cint ("1") 会失败?

c# - 是否可以通过反射调用私有(private)委托(delegate)?如果是那么如何?如果否,那么原因是什么?

java - 请参阅有关调用方法的 java 注释

java - 通过从注释属性获取的路径实例化对象