c# – 如何为我不拥有的类型和属性实现TypeConverter?

这很烦人:

<GeometryDrawing>
    <GeometryDrawing.Pen>
        <Pen Brush="Black"/>
    </GeometryDrawing.Pen>
</GeometryDrawing>

我要这个:

<GeometryDrawing Pen="Black"/>

所以我写了一个TypeConverter:

public class PenConverter : TypeConverter
{
    static readonly BrushConverter brushConverter = new BrushConverter();

    public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
    {
        if (sourceType == typeof(string)) return true;
        return base.CanConvertFrom(context, sourceType);
    }

    public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
    {
        var s = value as string;
        if (a != null)
        {
            var brush = brushConverter.ConvertFromInvariantString(s) as Brush;
            return new Pen(brush, 1);
        }
        return base.ConvertFrom(context, culture, value);
    }
}

现在,我如何将其与笔类型链接?我不能只为它添加一个TypeConverterAttribute,因为我没有它(我也没有GeometryDrawing.Pen属性).

最佳答案
This link here声称你可以做类似的事情(复制逐字,对那个人的信用)

public static void Register<T, TC>() where TC: TypeConverter
{
 Attribute[] attr = new Attribute[1];
 TypeConverterAttribute vConv = new TypeConverterAttribute(typeof(TC));
      attr[0] = vConv;
 TypeDescriptor.AddAttributes(typeof(T), attr);
}

该方法的最后一部分似乎可以解决问题.

点赞