Je dois afficher un objet dans PropertyGrid avec les conditions suivantes: l'objet et son sous-objet doivent être en lecture seule, capables d'activer les CollectionEditors de PropertyGrid.PropertyGrid en lecture seule
J'ai trouvé un échantillon qui correspond exactement à ce dont j'ai besoin, mais il y a un comportement inattendu que je n'ai pas pu comprendre. J'ai plus d'un PropertyGrids chacun pour différents objets. Dans SetBrowsablePropertiesAsReadOnly, je boucle un objet mais étonnamment tous les PropertyGrids dans mon projet deviennent readonly. Quelqu'un peut-il m'aider? Voici le code:
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