PropertyDescriptor Clase

Definición

Proporciona una abstracción de una propiedad en una clase.

public ref class PropertyDescriptor abstract : System::ComponentModel::MemberDescriptor
public abstract class PropertyDescriptor : System.ComponentModel.MemberDescriptor
[System.Runtime.InteropServices.ComVisible(true)]
public abstract class PropertyDescriptor : System.ComponentModel.MemberDescriptor
type PropertyDescriptor = class
    inherit MemberDescriptor
[<System.Runtime.InteropServices.ComVisible(true)>]
type PropertyDescriptor = class
    inherit MemberDescriptor
Public MustInherit Class PropertyDescriptor
Inherits MemberDescriptor
Herencia
PropertyDescriptor
Derivado
Atributos

Ejemplos

El ejemplo de código siguiente se basa en el ejemplo de la PropertyDescriptorCollection clase . Imprime la información (categoría, descripción, nombre para mostrar) del texto de un botón en un cuadro de texto. Se supone que button1 y textbox1 se han creado instancias en un formulario.

// 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" );
// 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';
' 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

En el ejemplo de código siguiente se muestra cómo implementar un descriptor de propiedades personalizado que proporciona un contenedor de solo lectura alrededor de una propiedad. SerializeReadOnlyPropertyDescriptor se usa en un diseñador personalizado para proporcionar un descriptor de propiedad de solo lectura para la propiedad del Size control.

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(nameof(existing));
            }

            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;
        }
    }
}
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 - 1
                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

En los ejemplos de código siguientes se muestra cómo usar en SerializeReadOnlyPropertyDescriptor un diseñador personalizado.

using System.Collections;
using System.ComponentModel;
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);
        }
    }
}
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
using System.ComponentModel;
using System.Windows.Forms;

namespace ReadOnlyPropertyDescriptorTest
{
    [Designer(typeof(DemoControlDesigner))]
    public class DemoControl : Control
    {
        public DemoControl()
        {
        }
    }
}
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

Comentarios

Una descripción de una propiedad consta de un nombre, sus atributos, la clase de componente a la que está asociada la propiedad y el tipo de la propiedad.

PropertyDescriptor proporciona las siguientes propiedades y métodos:

PropertyDescriptor también proporciona las siguientes abstract propiedades y métodos:

  • ComponentType contiene el tipo de componente al que está enlazada esta propiedad.

  • IsReadOnly indica si esta propiedad es de solo lectura.

  • PropertyType obtiene el tipo de la propiedad .

  • CanResetValue indica si el restablecimiento del componente cambia el valor del componente.

  • GetValue devuelve el valor actual de la propiedad en un componente.

  • ResetValue restablece el valor de esta propiedad del componente.

  • SetValue establece el valor del componente en un valor diferente.

  • ShouldSerializeValue indica si el valor de esta propiedad debe conservarse.

Normalmente, los abstract miembros se implementan a través de la reflexión. Para obtener más información sobre la reflexión, consulte los temas de Reflexión.

Constructores

PropertyDescriptor(MemberDescriptor)

Inicializa una nueva instancia de la clase PropertyDescriptor con el nombre y los atributos del MemberDescriptor especificado.

PropertyDescriptor(MemberDescriptor, Attribute[])

Inicializa una nueva instancia de la clase PropertyDescriptor con el nombre del MemberDescriptor especificado y los atributos de MemberDescriptor y la matriz Attribute.

PropertyDescriptor(String, Attribute[])

Inicializa una nueva instancia de la clase PropertyDescriptor con el nombre y los atributos especificados.

Propiedades

AttributeArray

Obtiene o establece una matriz de atributos.

(Heredado de MemberDescriptor)
Attributes

Obtiene la colección de atributos de este miembro.

(Heredado de MemberDescriptor)
Category

Obtiene el nombre de la categoría a la que pertenece el miembro, tal como se especifica en CategoryAttribute.

(Heredado de MemberDescriptor)
ComponentType

Cuando se reemplaza en una clase derivada, obtiene el tipo de componente al que está enlazada esta propiedad.

Converter

Obtiene el convertidor de tipos de esta propiedad.

Description

Obtiene la descripción del miembro tal como se especifica en DescriptionAttribute.

(Heredado de MemberDescriptor)
DesignTimeOnly

Obtiene si este miembro debe establecerse sólo en tiempo de diseño según se especifica en DesignOnlyAttribute.

(Heredado de MemberDescriptor)
DisplayName

Obtiene el nombre que se puede mostrar en una ventana, como la ventana Propiedades.

(Heredado de MemberDescriptor)
IsBrowsable

Obtiene un valor que indica si se puede examinar el miembro, según se especifica en BrowsableAttribute.

(Heredado de MemberDescriptor)
IsLocalizable

Obtiene un valor que indica si esta propiedad se debe traducir, según se especifica en LocalizableAttribute.

IsReadOnly

Cuando se reemplaza en una clase derivada, obtiene un valor que indica si esta propiedad es de sólo lectura.

Name

Obtiene el nombre del miembro.

(Heredado de MemberDescriptor)
NameHashCode

Obtiene el código hash para el nombre del miembro, según se especifica en GetHashCode().

(Heredado de MemberDescriptor)
PropertyType

Cuando se reemplaza en una clase derivada, obtiene el tipo de propiedad.

SerializationVisibility

Obtiene un valor que indica si esta propiedad se debe serializar, según se especifica en DesignerSerializationVisibilityAttribute.

SupportsChangeEvents

Obtiene un valor que indica si las notificaciones de cambios de valores para esta propiedad se pueden originar fuera del descriptor de propiedades.

Métodos

AddValueChanged(Object, EventHandler)

Habilita la notificación a otros objetos cuando cambia esta propiedad.

CanResetValue(Object)

Cuando se reemplaza en una clase derivada, devuelve si al restablecer un objeto cambia su valor.

CreateAttributeCollection()

Crea una colección de atributos mediante la matriz de atributos que se pasó al constructor.

(Heredado de MemberDescriptor)
CreateInstance(Type)

Crea una instancia del tipo especificado.

Equals(Object)

Compara esto con otro objeto para ver si son equivalentes.

FillAttributes(IList)

Agrega los atributos de PropertyDescriptor a la lista de atributos especificada en la clase principal.

FillAttributes(IList)

Cuando se reemplaza en una clase derivada, agrega los atributos de la clase heredada a la lista especificada de atributos en la clase principal.

(Heredado de MemberDescriptor)
GetChildProperties()

Devuelve el valor predeterminado de PropertyDescriptorCollection.

GetChildProperties(Attribute[])

Devuelve PropertyDescriptorCollection utilizando una matriz especificada de atributos como filtro.

GetChildProperties(Object)

Devuelve PropertyDescriptorCollection para un objeto especificado.

GetChildProperties(Object, Attribute[])

Devuelve PropertyDescriptorCollection de un objeto dado utilizando como filtro una matriz especificada de atributos.

GetEditor(Type)

Obtiene un editor del tipo especificado.

GetHashCode()

Devuelve el código hash de este objeto.

GetInvocationTarget(Type, Object)

Este método devuelve el objeto que se debe utilizar durante la invocación de miembros.

GetInvocationTarget(Type, Object)

Recupera el objeto que se debe utilizar durante la invocación de miembros.

(Heredado de MemberDescriptor)
GetType()

Obtiene el Type de la instancia actual.

(Heredado de Object)
GetTypeFromName(String)

Devuelve un tipo mediante su nombre.

GetValue(Object)

Cuando se reemplaza en una clase derivada, obtiene el valor actual de la propiedad de un componente.

GetValueChangedHandler(Object)

Recupera el conjunto actual de controladores de eventos ValueChanged para un componente concreto.

MemberwiseClone()

Crea una copia superficial del Object actual.

(Heredado de Object)
OnValueChanged(Object, EventArgs)

Provoca el evento ValueChanged que se ha implementado.

RemoveValueChanged(Object, EventHandler)

Habilita la notificación a otros objetos cuando cambia esta propiedad.

ResetValue(Object)

Cuando se reemplaza en una clase derivada, restablece el valor predeterminado de esta propiedad del componente.

SetValue(Object, Object)

Cuando se reemplaza en una clase derivada, establece el valor del componente en otro diferente.

ShouldSerializeValue(Object)

Cuando se reemplaza en una clase derivada, determina un valor que indica si el valor de esta propiedad debe almacenarse.

ToString()

Devuelve una cadena que representa el objeto actual.

(Heredado de Object)

Se aplica a

Consulte también