У меня есть следующий код, взятый из потока:
Повторное использование TypeConverter в PropertyGrid .NET winforms
Пример кода взят из ответа на вышеупомянутую тему Саймона Мурье
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);
}
}
Этот подход представляется возможным, поскольку я также видел, что на него ссылаются следующие два потока:
http://geekswithblogs.net/abhijeetp/archive/2009/01/10/dynamic-attributes-in-c.aspx
StringConverter GetStandardValueCollection
Я могу найти свойства с настраиваемым атрибутом ListTypeConverter в классе Animal и просмотреть их
var props = context.Instance.GetType().GetProperties().Where(
prop => Attribute.IsDefined(prop, typeof(ListTypeConverterAttribute))).ToList();
Проблема, с которой я столкнулся, заключается в том, что код, предоставленный Саймоном и другими, требует context.PropertyDescriptor, а в моем случае
context.PropertyDescriptor == null
Как найти свойство класса Animal, которое вызвало ListTypeConverter, чтобы я мог вернуть правильный список пользовательских атрибутов в
return new StandardValuesCollection(list);