Reputation: 2691
How can I get the PropertyDescriptor
for the current property? For example:
[MyAttribute("SomeText")]
public string MyProperty
{
get{....}
set
{
// here I want to get PropertyDescriptor for this property.
}
}
Upvotes: 13
Views: 40570
Reputation: 19881
I found that the following worked:
// get property descriptions
PropertyDescriptorCollection properties = TypeDescriptor.GetProperties ( this );
// get specific descriptor
PropertyDescriptor property = properties.Find ( PropertyName, false );
where PropertyName
is a value passed into a method.
Upvotes: 5
Reputation: 1149
For future reference, you can now do this:
public static PropertyDescriptor? GetPropertyDescriptor(
this object target,
[CallerMemberName] string propertyName = ""
) => TypeDescriptor.GetProperties(target.GetType())
.Find(propertyName, ignoreCase: false)
Upvotes: 0
Reputation: 22406
Here's a re-usable conversion function for those who got to this post looking for a general function:
public static PropertyDescriptor GetPropertyDescriptor(PropertyInfo PropertyInfo)
{
return TypeDescriptor.GetProperties(PropertyInfo.DeclaringType).Item(PropertyInfo.Name);
}
and here's an extension method:
public static PropertyDescriptor PropertyDescriptor(this PropertyInfo propertyInfo)
{
return TypeDescriptor.GetProperties(propertyInfo.DeclaringType)[propertyInfo.Name];
}
Upvotes: 12
Reputation: 18013
You could try this:
public string Test
{
get
{
//Get properties for this
System.ComponentModel.PropertyDescriptorCollection pdc = System.ComponentModel.TypeDescriptor.GetProperties( this );
//Get property descriptor for current property
System.ComponentModel.PropertyDescriptor pd = pdc[ System.Reflection.MethodBase.GetCurrentMethod().Name ];
}
}
Upvotes: 16
Reputation: 14783
How about this?
this.GetType().GetProperty("MyProperty")
I think you're asking if you can do this without the string - i.e. some other token that represents 'this property'. I don't think that exists. But since you are writing this code anyway (?) what is the difficulty in just putting the name of the property in the code?
Upvotes: 0