将具有可变自定义数据的自定义属性附加到PropertyGrid中的类属性

时间:2019-03-26 22:22:16

标签: c# .net wpf propertygrid

我从线程中获取了以下代码: TypeConverter reuse in PropertyGrid .NET winforms

代码示例摘自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);
    }
}

这种方法似乎可行,因为我也看到了以下两个线程中引用的方法: http://geekswithblogs.net/abhijeetp/archive/2009/01/10/dynamic-attributes-in-c.aspx StringConverter GetStandardValueCollection

我可以在Animal类中找到具有ListTypeConverter自定义属性的属性,并对其进行遍历

        var props = context.Instance.GetType().GetProperties().Where(
        prop => Attribute.IsDefined(prop, typeof(ListTypeConverterAttribute))).ToList();

我遇到的问题是Simon和其他人提供的代码需要context.PropertyDescriptor,就我而言

context.PropertyDescriptor == null

如何找到调用ListTypeConverter的Animal类属性,以便可以在

中返回正确的自定义属性列表
return new StandardValuesCollection(list);

0 个答案:

没有答案