I have the following code taken from the thread: TypeConverter reuse in PropertyGrid .NET winforms
The code sample is from the reply to the above thread by Simon Mourier
public class Animals
{
// both properties have the same TypeConverter, but they use different custom attributes
[TypeConverter(typeof(ListTypeConverter))]
[ListTypeConverter(new [] { "cat", "dog" })]
public string Pets { get; set; }
[TypeConverter(typeof(ListTypeConverter))]
[ListTypeConverter(new [] { "cow", "sheep" })]
public string Others { get; set; }
}
// this is your custom attribute
// Note attribute can only use constants (as they are added at compile time), so you can't add a List object here
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
public class ListTypeConverterAttribute : Attribute
{
public ListTypeConverterAttribute(string[] list)
{
List = list;
}
public string[] List { get; set; }
}
// this is the type converter that knows how to use the ListTypeConverterAttribute attribute
public class ListTypeConverter : TypeConverter
{
public override bool GetStandardValuesSupported(ITypeDescriptorContext context) => true;
public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context)
{
var list = new List<string>();
// the context contains the property descriptor
// the property descriptor has all custom attributes defined on the property
// just get it (with proper null handling)
var choices = context.PropertyDescriptor.Attributes.OfType<ListTypeConverterAttribute>().FirstOrDefault()?.List;
if (choices != null)
{
list.AddRange(choices);
}
return new StandardValuesCollection(list);
}
}
This approach seems to be possible as I have also seen it referenced in the following two threads: http://geekswithblogs.net/abhijeetp/archive/2009/01/10/dynamic-attributes-in-c.aspx StringConverter GetStandardValueCollection
I can find the properties with ListTypeConverter custom attribute in the Animal class, and iterate through them
var props = context.Instance.GetType().GetProperties().Where(
prop => Attribute.IsDefined(prop, typeof(ListTypeConverterAttribute))).ToList();
The issue I am having is that the code provided by Simon and the others requires the context.PropertyDescriptor, and in my case
context.PropertyDescriptor == null
How can I find the Animal class property that invoked the ListTypeConverter so that I can return the proper custom attribute list in the
return new StandardValuesCollection(list);