2

コントロールを使用し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もう一度設定するとすべてのプロパティが読み取り専用に設定されることです。誰かが私のコードにエラーを見ることができますか?

4

1 に答える 1

5

すべてのクラスプロパティを次の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で実行時にプロパティを有効/無効にします

これらすべてが適切に機能するためには、クラスのすべてのプロパティのReadOnly属性を必要な値に静的に定義することが重要です。そうでない場合、実行時にそのように属性を変更すると、クラスのすべてのプロパティの属性が誤って変更されます。

于 2012-06-12T13:32:05.193 に答える