views:

196

answers:

1

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

A: 

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.

Benjamin Podszun
That doesn't seem to work. I call AddAttributes before InitializeComponent and it still throws. :(
CannibalSmith
Did you check if the Typeconverter works at all after adding it by accessing TypeDescriptor.GetConverter(typeof(Pen))?
Benjamin Podszun
GetConverter returns my PenConverter alright.
CannibalSmith