我正在使用一个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
to True
,什么也没有发生,然后当我将其设置为False
它再次设置all属性只读。有人可以看到我的代码中的错误吗?
尝试用以下内容装饰你的所有类属性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 中启用/禁用属性 http://www.codeproject.com/Articles/152945/Enabling-disabling-properties-at-runtime-in-the-Pr
为了使这一切正常工作,将类的每个属性的 ReadOnly 属性静态定义为您想要的任何值非常重要。如果不是,那么在运行时更改属性将错误地修改类的每个属性的属性。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)