How does the XAML Parser convert the string "Red" in Foreground="Red" to a SolidColorBrush? Allthough I know the Types have System.ComponentModel.TypeConverter defined, I doupt that the WPF XAML parser acutally always uses those to convert the string to the brush. Are there any XAML APIs apart from XamlReader.Load (wich wants a valid xml string) that I could use to parse a single string as if it where an attibute for a certain property?
I believe you can take advantage of this yourself. XamlReader knows the target type (the type of the property to which the string must be applied). You would register a TypeConverter for that property's type.
EDIT this will work for you when it comes to SolidColorBrush
:
var colorString = ...;
var converter = new System.Windows.Media.BrushConverter();
var brush = (SolidColorBrush)converter.ConvertFromString(colorString);
Looking at SolidColorBrush
in .NET Reflector, it seems the magic that does deserialization within XamlReader
uses internal APIs around known types. I'm not sure whether you can register your own types to handle this.
The XAML parser (for WPF) really does actually use the type converter of the property or property type specified. There are a few hard-coded short-cuts but they are for performance and do not change the semantics. A parser, just using attribute information, can duplicate the parser semantics (which is, for example, what Blend and Cider do).
There is no API that will convert a value exactly as XAML would mainly because many type converts only work in the context of a XAML parse. For example, type converters can refer to namespaces defined in the XAML file (which changes depending on where the value is in the XML file) as well as other ambient information base URI base for the file. These are only really applicable when the XAML file is being parsed.
The closest you can come to is asking for the property descriptor for the property from the type descriptor and using the Converter property. This will scan the appropriate attributes to create the correct type converter.