PropertyDescriptor, classe
Mise à jour : novembre 2007
Fournit une abstraction d'une propriété sur une classe.
Assembly : System (dans System.dll)
[ComVisibleAttribute(true)] [HostProtectionAttribute(SecurityAction.LinkDemand, SharedState = true)] public abstract class PropertyDescriptor : MemberDescriptor
/** @attribute ComVisibleAttribute(true) */ /** @attribute HostProtectionAttribute(SecurityAction.LinkDemand, SharedState = true) */ public abstract class PropertyDescriptor extends MemberDescriptor
public abstract class PropertyDescriptor extends MemberDescriptor
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. |
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 :
Converter contient TypeConverter pour cette propriété.
IsLocalizable indique si cette propriété doit être localisée.
GetEditor retourne un éditeur du type spécifié.
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.
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.
// 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.
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.set_Text(myProperty.get_DisplayName() + 'n');
textBox1.set_Text(textBox1.get_Text() + myProperty.get_Description()
+ '\n');
textBox1.set_Text(textBox1.get_Text() + myProperty.get_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.
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é.
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() { } } }
System.ComponentModel.MemberDescriptor
System.ComponentModel.PropertyDescriptor
System.ComponentModel.DependencyPropertyDescriptor
System.ComponentModel.TypeConverter.SimplePropertyDescriptor
Windows Vista, Windows XP SP2, Windows XP Media Center Edition, Windows XP Professionnel Édition x64, Windows XP Starter Edition, Windows Server 2003, Windows Server 2000 SP4, Windows Millennium Edition, Windows 98, Windows CE, Windows Mobile pour Smartphone, Windows Mobile pour Pocket PC, Xbox 360
Le .NET Framework et le .NET Compact Framework ne prennent pas en charge toutes les versions de chaque plateforme. Pour obtenir la liste des versions prises en charge, consultez Configuration requise du .NET Framework.
Remarque :