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

Posted by CannibalSmith on Stack Overflow See other posts from Stack Overflow or by CannibalSmith
Published on 2010-01-04T14:22:11Z Indexed on 2010/04/01 8:03 UTC
Read the original article Hit count: 214

Filed under:
|
|
|

This is annoying:

<GeometryDrawing>
    <GeometryDrawing.Pen>
        <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).

© Stack Overflow or respective owner

Related posts about xaml

Related posts about c#