pertyGrid中设置ReadOnly属性会将所有属性设置为只

pertyGrid中设置ReadOnly属性会将所有属性设置为只

本文介绍了在PropertyGrid中设置ReadOnly属性会将所有属性设置为只读的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

这是我班上的代码:

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

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

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?

推荐答案

尝试使用ReadOnly属性装饰所有的类属性:

Try decorating ALL of your class properties with the ReadOnly attribute:

<[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中

Found it from this Code Project: Enabling/disabling properties at runtime in the PropertyGrid

这篇关于在PropertyGrid中设置ReadOnly属性会将所有属性设置为只读的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-31 08:19