Question

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.
    }
}
Was it helpful?

Solution

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

OTHER TIPS

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

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.

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?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top