开发者

How to implement a TypeConverter for a type and property I don't own?

开发者 https://www.devze.com 2022-12-15 04:50 出处:网络
This is annoying: <GeometryDrawing> <GeometryDrawing.Pen> 开发者_JAVA百科<Pen Brush=\"Black\"/>

This is annoying:

<GeometryDrawing>
    <GeometryDrawing.Pen>
      开发者_JAVA百科  <Pen Brush="Black"/>
    </GeometryDrawing.Pen>
</GeometryDrawing>

I want this:

<GeometryDrawing Pen="Black"/>

So I write a 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);
    }
}

Now, how do I link it up with the Pen type? I can't just add a TypeConverterAttribute to it as I don't own it (nor do I own GeometryDrawing.Pen property).


This link here claims you can do something like (copied verbatim, credits to that guy)

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);
}

The last part of that method seems to do the trick.


The answer by Benjamin Podszun does not work here because the XAML parser appears to ignore attributes added via the TypeDescriptor, bindings however do not, so you could use one to work around this:

<GeometryDrawing Pen="{Binding Source=Black}"/>

Not very elegant i concede, similarily you could use a markup extension as a pen factory...

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号