2012-06-12 2 views
2

PropertyGrid 컨트롤을 사용하여 클래스 속성을 편집하고 다른 속성 설정에 따라 특정 속성을 읽기 전용으로 설정하려고합니다.PropertyGrid의 ReadOnly 속성 설정 Readonly 모든 속성 설정

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 

문제는 그 나는 TrueSomeProperty, 아무것도 설정하지 않을 때 그런 다음 False으로 다시 설정하면 모두 속성이 읽기 전용으로 설정됩니다. 누군가 내 코드에서 오류를 볼 수 있습니까? ReadOnly 속성을 가진 클래스의 모든 속성을 장식

답변

5

시도 :이 코드 프로젝트에서 발견

<[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 특성을 원하는 값으로 정적으로 정의합니다. 그렇지 않은 경우 런타임에 속성을 변경하면 클래스의 모든 속성의 속성이 잘못 수정됩니다.

+0

Brilliant - Thanks Lars –