2012-06-12 243 views
2

我正在使用PropertyGrid控件編輯我的類屬性,我試圖根據其他屬性設置將某些屬性設置爲只讀。在PropertyGrid中設置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 

的問題是,當我設置SomePropertyTrue,沒什麼發生時,然後當我再次將其設置爲False時,它會設置全部屬性只讀。有人可以在我的代碼中看到錯誤嗎?

回答

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 

從這個代碼項目發現:Enabling/disabling properties at runtime in the PropertyGrid

爲了讓這一切都正常工作,這是很重要靜態地將類的每個屬性的ReadOnly屬性定義爲你想要的任何值。如果不是,那麼在運行時改變屬性將會錯誤地修改該類的每個屬性的屬性。

+0

輝煌 - 謝謝拉爾斯 –