2

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 

Répondre

0

L'attribut ReadOnly est défini sur la définition de la classe, et non pas sur une instance d'un objet. Par conséquent, cela aura un impact sur toutes les instances de cette classe.

Pour obtenir ce que vous voulez, créez un PropertyDescriptor personnalisé dans lequel vous remplacez la propriété IsReadOnly et appliquez-le aux propriétés de votre instance d'objet.

0

Je suis sûr que ce n'est pas une syntaxe correcte vb mais cela peut être fait en ajoutant un attribut:

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 
Questions connexes