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...
精彩评论