首页 > 解决方案 > 将具有可变自定义数据的自定义属性附加到 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);

标签: c#.netwpfpropertygrid

解决方案


推荐阅读