PropertyDescriptor, classe (System.ComponentModel)

Changer de vue:
ScriptFree
Bibliothèque de classes .NET Framework
PropertyDescriptor, classe
Cet article a fait l'objet d'une traduction manuelle. Pour afficher simultanément cette page et le contenu source en anglais, choisissez le paramètre d'affichage Basse densité.

Fournit une abstraction d'une propriété sur une classe.

Hiérarchie d'héritage

System.Object
  System.ComponentModel.MemberDescriptor
    System.ComponentModel.PropertyDescriptor
      System.ComponentModel.DependencyPropertyDescriptor
      System.ComponentModel.TypeConverter.SimplePropertyDescriptor

Espace de noms :  System.ComponentModel
Assembly :  System (dans System.dll)
Syntaxe

Visual Basic
<ComVisibleAttribute(True)> _
<HostProtectionAttribute(SecurityAction.LinkDemand, SharedState := True)> _
Public MustInherit Class PropertyDescriptor _
	Inherits MemberDescriptor
C#
[ComVisibleAttribute(true)]
[HostProtectionAttribute(SecurityAction.LinkDemand, SharedState = true)]
public abstract class PropertyDescriptor : MemberDescriptor
VisualC++
[ComVisibleAttribute(true)]
[HostProtectionAttribute(SecurityAction::LinkDemand, SharedState = true)]
public ref class PropertyDescriptor abstract : public MemberDescriptor
F#
[<AbstractClass>]
[<ComVisibleAttribute(true)>]
[<HostProtectionAttribute(SecurityAction.LinkDemand, SharedState = true)>]
type PropertyDescriptor =  
    class
        inherit MemberDescriptor
    end

Le type PropertyDescriptor expose les membres suivants.

Constructeurs

  Nom Description
Méthode protégée Pris en charge par XNA Framework PropertyDescriptor(MemberDescriptor) Initialise une nouvelle instance de la classe PropertyDescriptor avec le nom et les attributs dans le MemberDescriptor spécifié.
Méthode protégée Pris en charge par XNA Framework PropertyDescriptor(MemberDescriptor, Attribute[]) Initialise une nouvelle instance de la classe PropertyDescriptor avec le nom dans le MemberDescriptor spécifié et les attributs dans MemberDescriptor et le tableau Attribute.
Méthode protégée Pris en charge par XNA Framework PropertyDescriptor(String, Attribute[]) Initialise une nouvelle instance de la classe PropertyDescriptor avec le nom et les attributs spécifiés.
Début
Propriétés

  Nom Description
Propriété protégée Pris en charge par XNA Framework AttributeArray Obtient ou définit un tableau d'attributs. (Hérité de MemberDescriptor.)
Propriété publique Attributes Obtient la collection des attributs de ce membre. (Hérité de MemberDescriptor.)
Propriété publique Category Obtient le nom de la catégorie à laquelle le membre appartient, comme spécifié dans CategoryAttribute. (Hérité de MemberDescriptor.)
Propriété publique Pris en charge par XNA Framework ComponentType En cas de substitution dans une classe dérivée, obtient le type du composant auquel cette propriété est liée.
Propriété publique Converter Obtient le convertisseur de type pour cette propriété.
Propriété publique Description Obtient la description du membre, telle qu'elle est spécifiée dans DescriptionAttribute. (Hérité de MemberDescriptor.)
Propriété publique DesignTimeOnly Obtient une valeur indiquant si ce membre ne doit être défini qu'au moment du design, comme spécifié dans DesignOnlyAttribute. (Hérité de MemberDescriptor.)
Propriété publique Pris en charge par XNA Framework DisplayName Obtient le nom qui peut être affiché dans une fenêtre, telle qu'une fenêtre Propriétés. (Hérité de MemberDescriptor.)
Propriété publique IsBrowsable Obtient une valeur indiquant si le membre peut être exploré, tel que spécifié dans BrowsableAttribute. (Hérité de MemberDescriptor.)
Propriété publique IsLocalizable Obtient une valeur indiquant si cette propriété doit être localisée, comme spécifié dans LocalizableAttribute.
Propriété publique Pris en charge par XNA Framework IsReadOnly En cas de substitution dans une classe dérivée, obtient une valeur indiquant si cette propriété est en lecture seule.
Propriété publique Pris en charge par XNA Framework Name Obtient le nom du membre. (Hérité de MemberDescriptor.)
Propriété protégée Pris en charge par XNA Framework NameHashCode Obtient le code de hachage pour le nom du membre, tel que spécifié dans GetHashCode. (Hérité de MemberDescriptor.)
Propriété publique Pris en charge par XNA Framework PropertyType En cas de substitution dans une classe dérivée, obtient le type de la propriété.
Propriété publique SerializationVisibility Obtient une valeur indiquant si cette propriété doit être sérialisée, comme spécifié dans DesignerSerializationVisibilityAttribute.
Propriété publique Pris en charge par XNA Framework SupportsChangeEvents Obtient une valeur qui indique si les notifications de modification des valeurs pour cette propriété peuvent provenir de l'extérieur du descripteur de propriété.
Début
Méthodes

  Nom Description
Méthode publique Pris en charge par XNA Framework AddValueChanged Permet à d'autres objets d'être avertis en cas de modification de cette propriété.
Méthode publique Pris en charge par XNA Framework CanResetValue En cas de substitution dans une classe dérivée, retourne une valeur indiquant si la réinitialisation d'un objet modifie sa valeur.
Méthode protégée Pris en charge par XNA Framework CreateAttributeCollection Crée une collection d'attributs à l'aide du tableau d'attributs passé au constructeur. (Hérité de MemberDescriptor.)
Méthode protégée CreateInstance Crée une instance du type spécifié.
Méthode publique Pris en charge par XNA Framework Equals Compare cet objet à un autre afin de déterminer s'ils sont équivalents. (Substitue MemberDescriptor.Equals(Object).)

Dans XNA Framework 3.0, ce membre est hérité de Object.Equals(Object).
Méthode protégée Pris en charge par XNA Framework FillAttributes Ajoute les attributs de PropertyDescriptor à la liste spécifiée d'attributs dans la classe parente. (Substitue MemberDescriptor.FillAttributes(IList).)

Dans XNA Framework 3.0, ce membre est hérité de MemberDescriptor.FillAttributes(IList).
Méthode protégée Pris en charge par XNA Framework Finalize Autorise un objet à tenter de libérer des ressources et d'exécuter d'autres opérations de netto***ge avant qu'il ne soit récupéré par l'opération garbage collection. (Hérité de Object.)
Méthode publique GetChildProperties() Retourne le PropertyDescriptorCollection par défaut.
Méthode publique GetChildProperties(Attribute[]) Retourne un PropertyDescriptorCollection avec comme filtre un tableau d'attributs spécifié.
Méthode publique GetChildProperties(Object) Retourne un PropertyDescriptorCollection pour un objet donné.
Méthode publique GetChildProperties(Object, Attribute[]) Retourne un PropertyDescriptorCollection pour un objet donné à l'aide d'un tableau d'attributs spécifié comme filtre.
Méthode publique GetEditor Obtient un éditeur du type spécifié.
Méthode publique Pris en charge par XNA Framework GetHashCode Retourne le code de hachage de cet objet. (Substitue MemberDescriptor.GetHashCode().)

Dans XNA Framework, ce membre est substitué par GetHashCode().
Méthode protégée GetInvocationTarget Cette méthode retourne l'objet qui doit être utilisé pendant l'appel de membres. (Substitue MemberDescriptor.GetInvocationTarget(Type, Object).)
Méthode publique Pris en charge par XNA Framework GetType Obtient le Type de l'instance actuelle. (Hérité de Object.)
Méthode protégée GetTypeFromName Retourne un type en utilisant son nom.
Méthode publique Pris en charge par XNA Framework GetValue En cas de substitution dans une classe dérivée, obtient la valeur actuelle de la propriété d'un composant.
Méthode protégée Pris en charge par XNA Framework GetValueChangedHandler Récupère l'ensemble actuel de gestionnaires d'événements ValueChanged pour un composant spécifique.
Méthode protégée Pris en charge par XNA Framework MemberwiseClone Crée une copie superficielle de l'objet Object actif. (Hérité de Object.)
Méthode protégée Pris en charge par XNA Framework OnValueChanged Déclenche l'événement ValueChanged que vous avez implémenté.
Méthode publique Pris en charge par XNA Framework RemoveValueChanged Permet à d'autres objets d'être avertis en cas de modification de cette propriété.
Méthode publique Pris en charge par XNA Framework ResetValue En cas de substitution dans une classe dérivée, rétablit la valeur par défaut de cette propriété du composant.
Méthode publique Pris en charge par XNA Framework SetValue En cas de substitution dans une classe dérivée, affecte une autre valeur au composant.
Méthode publique Pris en charge par XNA Framework ShouldSerializeValue En cas de substitution dans une classe dérivée, détermine une valeur indiquant si la valeur de cette propriété doit être persistante.
Méthode publique Pris en charge par XNA Framework ToString Retourne une chaîne qui représente l'objet actuel. (Hérité de Object.)
Début
Notes

Une description de propriété est constituée d'un nom, de ses attributs, de la classe de composants à laquelle cette propriété est associée, ainsi que du type de la propriété.

PropertyDescriptor fournit les propriétés et méthodes suivantes :

PropertyDescriptor fournit également les propriétés et les méthodes abstract suivantes :

  • ComponentType contient le type de composant auquel cette propriété est liée.

  • IsReadOnly indique si cette propriété est en lecture seule.

  • PropertyType obtient le type de la propriété.

  • CanResetValue indique si la réinitialisation du composant modifie sa valeur.

  • GetValue retourne la valeur actuelle de la propriété d'un composant.

  • ResetValue rétablit la valeur de cette propriété du composant.

  • SetValue affecte une autre valeur au composant.

  • ShouldSerializeValue indique si la valeur de cette propriété doit être persistante.

En général, les membres abstract sont implémentés par réflexion. Pour plus d'informations sur la réflexion, consultez les rubriques dans Réflexion.

Remarque Remarque

L'attribut HostProtectionAttribute appliqué à ce type ou membre a la valeur de propriété Resources suivante : SharedState. HostProtectionAttribute n'affecte pas les applications bureautiques (qui sont généralement démarrées en double-cliquant sur une icône, en tapant une commande ou en entrant une URL dans un navigateur). Pour plus d'informations, consultez la classe HostProtectionAttribute ou Attributs de programmation et de protection des hôtes SQL Server.

Exemples

L'exemple de code suivant s'appuie sur l'exemple fourni dans la classe PropertyDescriptorCollection. Il imprime les informations (catégorie, description, nom complet) du texte d'un bouton dans une zone de texte. Il suppose que button1 et textbox1 ont été instanciés dans un formulaire.

Visual Basic

' Creates a new collection and assign it the properties for button1.
Dim properties As PropertyDescriptorCollection = TypeDescriptor.GetProperties(Button1)

' Sets an PropertyDescriptor to the specific property.
Dim myProperty As PropertyDescriptor = properties.Find("Text", False)

' Prints the property and the property description.
TextBox1.Text += myProperty.DisplayName & Microsoft.VisualBasic.ControlChars.Cr
TextBox1.Text += myProperty.Description & Microsoft.VisualBasic.ControlChars.Cr
TextBox1.Text += myProperty.Category & Microsoft.VisualBasic.ControlChars.Cr


C#

// Creates a new collection and assign it the properties for button1.
PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(button1);

// Sets an PropertyDescriptor to the specific property.
System.ComponentModel.PropertyDescriptor myProperty = properties.Find("Text", false);

// Prints the property and the property description.
textBox1.Text = myProperty.DisplayName+ '\n' ;
textBox1.Text += myProperty.Description + '\n';
textBox1.Text += myProperty.Category + '\n';


VisualC++

// Creates a new collection and assign it the properties for button1.
PropertyDescriptorCollection^ properties = TypeDescriptor::GetProperties( button1 );

// Sets an PropertyDescriptor to the specific property.
System::ComponentModel::PropertyDescriptor^ myProperty = properties->Find( "Text", false );

// Prints the property and the property description.
textBox1->Text = String::Concat( myProperty->DisplayName, "\n" );
textBox1->Text = String::Concat( textBox1->Text, myProperty->Description, "\n" );
textBox1->Text = String::Concat( textBox1->Text, myProperty->Category, "\n" );


L'exemple de code suivant indique comment implémenter un descripteur de propriété personnalisé qui fournit un wrapper en lecture seule autour d'une propriété. Le SerializeReadOnlyPropertyDescriptor est utilisé dans un concepteur personnalisé pour fournir un descripteur de propriété en lecture seule pour la propriété Size du contrôle.

Visual Basic

Imports System
Imports System.Collections
Imports System.ComponentModel
Imports System.Text

' The SerializeReadOnlyPropertyDescriptor shows how to implement a 
' custom property descriptor. It provides a read-only wrapper 
' around the specified PropertyDescriptor. 
Friend NotInheritable Class SerializeReadOnlyPropertyDescriptor
    Inherits PropertyDescriptor
    Private _pd As PropertyDescriptor = Nothing


    Public Sub New(ByVal pd As PropertyDescriptor)
        MyBase.New(pd)
        Me._pd = pd

    End Sub


    Public Overrides ReadOnly Property Attributes() As AttributeCollection
        Get
            Return AppendAttributeCollection(Me._pd.Attributes, ReadOnlyAttribute.Yes)
        End Get
    End Property


    Protected Overrides Sub FillAttributes(ByVal attributeList As IList)
        attributeList.Add(ReadOnlyAttribute.Yes)

    End Sub


    Public Overrides ReadOnly Property ComponentType() As Type
        Get
            Return Me._pd.ComponentType
        End Get
    End Property


    ' The type converter for this property.
    ' A translator can overwrite with its own converter.
    Public Overrides ReadOnly Property Converter() As TypeConverter
        Get
            Return Me._pd.Converter
        End Get
    End Property


    ' Returns the property editor 
    ' A translator can overwrite with its own editor.
    Public Overrides Function GetEditor(ByVal editorBaseType As Type) As Object
        Return Me._pd.GetEditor(editorBaseType)

    End Function

    ' Specifies the property is read only.
    Public Overrides ReadOnly Property IsReadOnly() As Boolean
        Get
            Return True
        End Get
    End Property


    Public Overrides ReadOnly Property PropertyType() As Type
        Get
            Return Me._pd.PropertyType
        End Get
    End Property


    Public Overrides Function CanResetValue(ByVal component As Object) As Boolean
        Return Me._pd.CanResetValue(component)

    End Function


    Public Overrides Function GetValue(ByVal component As Object) As Object
        Return Me._pd.GetValue(component)

    End Function


    Public Overrides Sub ResetValue(ByVal component As Object)
        Me._pd.ResetValue(component)

    End Sub


    Public Overrides Sub SetValue(ByVal component As Object, ByVal val As Object)
        Me._pd.SetValue(component, val)

    End Sub

    ' Determines whether a value should be serialized.
    Public Overrides Function ShouldSerializeValue(ByVal component As Object) As Boolean
        Dim result As Boolean = Me._pd.ShouldSerializeValue(component)

        If Not result Then
            Dim dva As DefaultValueAttribute = _
                CType(_pd.Attributes(GetType(DefaultValueAttribute)), DefaultValueAttribute)
            If Not (dva Is Nothing) Then
                result = Not [Object].Equals(Me._pd.GetValue(component), dva.Value)
            Else
                result = True
            End If
        End If

        Return result

    End Function


    ' The following Utility methods create a new AttributeCollection
    ' by appending the specified attributes to an existing collection.
    Public Shared Function AppendAttributeCollection( _
        ByVal existing As AttributeCollection, _
        ByVal ParamArray newAttrs() As Attribute) As AttributeCollection

        Return New AttributeCollection(AppendAttributes(existing, newAttrs))

    End Function

    Public Shared Function AppendAttributes( _
        ByVal existing As AttributeCollection, _
        ByVal ParamArray newAttrs() As Attribute) As Attribute()

        If existing Is Nothing Then
            Throw New ArgumentNullException("existing")
        End If

        If newAttrs Is Nothing Then
            newAttrs = New Attribute(-1) {}
        End If

        Dim attributes() As Attribute

        Dim newArray(existing.Count + newAttrs.Length) As Attribute
        Dim actualCount As Integer = existing.Count
        existing.CopyTo(newArray, 0)

        Dim idx As Integer
        For idx = 0 To newAttrs.Length
            If newAttrs(idx) Is Nothing Then
                Throw New ArgumentNullException("newAttrs")
            End If

            ' Check if this attribute is already in the existing
            ' array.  If it is, replace it.
            Dim match As Boolean = False
            Dim existingIdx As Integer
            For existingIdx = 0 To existing.Count
                If newArray(existingIdx).TypeId.Equals(newAttrs(idx).TypeId) Then
                    match = True
                    newArray(existingIdx) = newAttrs(idx)
                    Exit For
                End If
            Next existingIdx

            If Not match Then
                actualCount += 1
                newArray(actualCount) = newAttrs(idx)
            End If
        Next idx

        ' If some attributes were collapsed, create a new array.
        If actualCount < newArray.Length Then
            attributes = New Attribute(actualCount) {}
            Array.Copy(newArray, 0, attributes, 0, actualCount)
        Else
            attributes = newArray
        End If

        Return attributes

    End Function
End Class


C#

using System;
using System.Collections;
using System.ComponentModel;
using System.Text;

namespace ReadOnlyPropertyDescriptorTest
{
    // The SerializeReadOnlyPropertyDescriptor shows how to implement a 
    // custom property descriptor. It provides a read-only wrapper 
    // around the specified PropertyDescriptor. 
    internal sealed class SerializeReadOnlyPropertyDescriptor : PropertyDescriptor
    {
        private PropertyDescriptor _pd = null;

        public SerializeReadOnlyPropertyDescriptor(PropertyDescriptor pd)
            : base(pd)
        {
            this._pd = pd;
        }

        public override AttributeCollection Attributes
        {
            get
            {
                return( AppendAttributeCollection(
                    this._pd.Attributes, 
                    ReadOnlyAttribute.Yes) );
            }
        }

        protected override void FillAttributes(IList attributeList)
        {
            attributeList.Add(ReadOnlyAttribute.Yes);
        }

        public override Type ComponentType
        {
            get
            {
                return this._pd.ComponentType;
            }
        }


        // The type converter for this property.
        // A translator can overwrite with its own converter.
        public override TypeConverter Converter
        {
            get
            {
                return this._pd.Converter;
            }
        }


        // Returns the property editor 
        // A translator can overwrite with its own editor.
        public override object GetEditor(Type editorBaseType)
        {
            return this._pd.GetEditor(editorBaseType);
        }

        // Specifies the property is read only.
        public override bool IsReadOnly
        {
            get
            {
                return true;
            }
        }

        public override Type PropertyType
        {
            get
            {
                return this._pd.PropertyType;
            }
        }

        public override bool CanResetValue(object component)
        {
            return this._pd.CanResetValue(component);
        }


        public override object GetValue(object component)
        {
            return this._pd.GetValue(component);
        }

        public override void ResetValue(object component)
        {
            this._pd.ResetValue(component);
        }

        public override void SetValue(object component, object val)
        {
            this._pd.SetValue(component, val);
        }

        // Determines whether a value should be serialized.
        public override bool ShouldSerializeValue(object component)
        {
            bool result = this._pd.ShouldSerializeValue(component);

            if (!result)
            {
                DefaultValueAttribute dva = (DefaultValueAttribute)_pd.Attributes[typeof(DefaultValueAttribute)];
                if (dva != null)
                {
                    result = !Object.Equals(this._pd.GetValue(component), dva.Value);
                }
                else
                {
                    result = true;
                }
            }

            return result;
        }

        // The following Utility methods create a new AttributeCollection
        // by appending the specified attributes to an existing collection.
        static public AttributeCollection AppendAttributeCollection(
            AttributeCollection existing, 
            params Attribute[] newAttrs)
        {
            return new AttributeCollection(AppendAttributes(existing, newAttrs));
        }


        static public Attribute[] AppendAttributes(
            AttributeCollection existing, 
            params Attribute[] newAttrs)
        {
            if (existing == null)
            {
                throw new ArgumentNullException("existing");
            }

            if (newAttrs == null)
            {
                newAttrs = new Attribute[0];
            }

            Attribute[] attributes;

            Attribute[] newArray = new Attribute[existing.Count + newAttrs.Length];
            int actualCount = existing.Count;
            existing.CopyTo(newArray, 0);

            for (int idx = 0; idx < newAttrs.Length; idx++)
            {
                if (newAttrs[idx] == null)
                {
                    throw new ArgumentNullException("newAttrs");
                }

                // Check if this attribute is already in the existing
                // array.  If it is, replace it.
                bool match = false;
                for (int existingIdx = 0; existingIdx < existing.Count; existingIdx++)
                {
                    if (newArray[existingIdx].TypeId.Equals(newAttrs[idx].TypeId))
                    {
                        match = true;
                        newArray[existingIdx] = newAttrs[idx];
                        break;
                    }
                }

                if (!match)
                {
                    newArray[actualCount++] = newAttrs[idx];
                }
            }

            // If some attributes were collapsed, create a new array.
            if (actualCount < newArray.Length)
            {
                attributes = new Attribute[actualCount];
                Array.Copy(newArray, 0, attributes, 0, actualCount);
            }
            else
            {
                attributes = newArray;
            }

            return attributes;
        }
    }
}


Les exemples de code suivants indiquent comment utiliser le SerializeReadOnlyPropertyDescriptor dans un concepteur personnalisé.

Visual Basic

Imports System
Imports System.Collections
Imports System.ComponentModel
Imports System.Text
Imports System.Windows.Forms.Design

Class DemoControlDesigner
    Inherits ControlDesigner

    ' The PostFilterProperties method replaces the control's 
    ' Size property with a read-only Size property by using 
    ' the SerializeReadOnlyPropertyDescriptor class.
    Protected Overrides Sub PostFilterProperties(ByVal properties As IDictionary) 
        If properties.Contains("Size") Then
            Dim original As PropertyDescriptor = properties("Size")

            Dim readOnlyDescriptor As New SerializeReadOnlyPropertyDescriptor(original)

            properties("Size") = readOnlyDescriptor
        End If

        MyBase.PostFilterProperties(properties)

    End Sub
End Class


...


Imports System
Imports System.ComponentModel
Imports System.ComponentModel.Design
Imports System.Text
Imports System.Windows.Forms
Imports System.Windows.Forms.Design


<Designer(GetType(DemoControlDesigner))>  _
Public Class DemoControl
    Inherits Control

    Public Sub New() 

    End Sub
End Class


C#

using System;
using System.Collections;
using System.ComponentModel;
using System.Text;
using System.Windows.Forms.Design;

namespace ReadOnlyPropertyDescriptorTest
{   
    class DemoControlDesigner : ControlDesigner
    {
        // The PostFilterProperties method replaces the control's 
        // Size property with a read-only Size property by using 
        // the SerializeReadOnlyPropertyDescriptor class.
        protected override void PostFilterProperties(IDictionary properties)
        {
            if (properties.Contains("Size"))
            {
                PropertyDescriptor original = properties["Size"] as PropertyDescriptor;
                SerializeReadOnlyPropertyDescriptor readOnlyDescriptor = 
                    new SerializeReadOnlyPropertyDescriptor(original);

                properties["Size"] = readOnlyDescriptor;
            }

            base.PostFilterProperties(properties);
        }
    }
}


...


using System;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Text;
using System.Windows.Forms;
using System.Windows.Forms.Design;

namespace ReadOnlyPropertyDescriptorTest
{
    [Designer(typeof(DemoControlDesigner))]
    public class DemoControl : Control
    {
        public DemoControl()
        {

        }
    }
}


Informations de version

.NET Framework

Pris en charge dans : 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework Client Profile

Pris en charge dans : 4, 3.5 SP1
Plateformes

Windows 7, Windows Vista SP1 ou ultérieur, Windows XP SP3, Windows XP SP2 Édition x64, Windows Server 2008 (installation minimale non prise en charge), Windows Server 2008 R2 (installation minimale prise en charge avec SP1 ou version ultérieure), Windows Server 2003 SP2

Le .NET Framework ne prend pas en charge toutes les versions de chaque plateforme. Pour obtenir la liste des versions prises en charge, consultez Configuration requise du .NET Framework.
Sécurité des threads

Tous les membres static (Shared en Visual Basic) publics de ce type sont thread-safe. Il n'est pas garanti que les membres d'instance soient thread-safe.
Voir aussi

Référence