首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >只读PropertyGrid

只读PropertyGrid
EN

Stack Overflow用户
提问于 2008-12-15 04:03:29
回答 2查看 1.4K关注 0票数 2

我需要在PropertyGrid中显示一个满足以下要求的对象:该对象及其子对象必须是只读的,能够激活PropertyGrid的CollectionEditors。

我找到了一个与我需要的非常匹配的样本,但有一种意想不到的行为我搞不懂。对于不同的对象,我有多个PropertyGrids。在SetBrowsablePropertiesAsReadOnly中,我循环了一个对象,但令人惊讶的是,我的项目中的所有PropertyGrids都是只读的。有人能帮我吗。代码如下:

代码语言:javascript
复制
Imports System.Reflection
Imports System.ComponentModel

Public Class PropertyGridEx
    Inherits PropertyGrid

    Private isReadOnly As Boolean
    Public Property [ReadOnly]() As Boolean
        Get
            Return Me.isReadOnly
        End Get
        Set(ByVal value As Boolean)
            Me.isReadOnly = value
            Me.SetBrowsablePropertiesAsReadOnly(Me.SelectedObject, value)
        End Set
    End Property

    Protected Overloads Sub OnSelectedObjectsChanged(ByVal e As EventArgs)
        Me.SetBrowsablePropertiesAsReadOnly(Me.SelectedObject, Me.isReadOnly)
        MyBase.OnSelectedObjectsChanged(e)
    End Sub

    Private Sub SetBrowsablePropertiesAsReadOnly(ByRef selectedObject As Object, ByVal isReadOnly As Boolean)
        If selectedObject IsNot Nothing Then
            Dim props As PropertyDescriptorCollection = TypeDescriptor.GetProperties(selectedObject)
            For Each propDescript As PropertyDescriptor In props
                If propDescript.IsBrowsable AndAlso propDescript.PropertyType.GetInterface("ICollection", True) Is Nothing Then
                    Dim attr As ReadOnlyAttribute = TryCast(propDescript.Attributes(GetType(ReadOnlyAttribute)), ReadOnlyAttribute)
                    If attr IsNot Nothing Then
                        Dim field As FieldInfo = attr.[GetType]().GetField("isReadOnly", BindingFlags.NonPublic Or BindingFlags.Instance)
                        field.SetValue(attr, isReadOnly, BindingFlags.NonPublic Or BindingFlags.Instance, Nothing, Nothing)
                    End If
                End If
            Next
        End If
    End Sub
End Class
EN

回答 2

Stack Overflow用户

发布于 2009-03-04 11:05:38

ReadOnly属性在类定义上设置,而不是在对象的实例上设置。因此,这将对该类的所有实例产生影响。

要实现所需的功能,请创建一个在其中覆盖IsReadOnly属性的自定义PropertyDescriptor,并将其应用于对象实例的属性。

票数 0
EN

Stack Overflow用户

发布于 2012-01-04 13:39:13

我确信这不是正确的vb语法,但这可以通过添加一个属性来完成:

代码语言:javascript
复制
Private Sub SetBrowsablePropertiesAsReadOnly(ByRef selectedObject As Object, ByVal isReadOnly As Boolean)
  If selectedObject IsNot Nothing Then
    TypeDescriptor.AddAttributes(selectedObject, New Attribute[] { New ReadOnlyAttribute(isReadOnly) });
  End If
End Sub
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/367444

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档