In chapter 2 of the book WPF4 Unleashed the author shows an example of how XAML processes type conversion. He states that
<SolidColorBrush>White</SolidColorBrush>
is equivalent to
<SolidColorBrush Color="White"/>
, because a string can be converted into a SolidColorBrush
object.
But how is that enough? It doesn’t make sense to me. How does XAML know to which property should the value White
be assigned?
2
This is a core feature of XAML. Microsoft’s XAML Overview covers this rather explicitly.
A small number of XAML elements can directly process text as their content. To enable this, one of the following cases must be true:
The class must declare a content property, and that content property must be of a type assignable to a string (the type could be Object). For instance, any ContentControl uses Content as its content property and it is type Object, and this supports the following usage on a practical ContentControl such as a Button: Hello.
The type must declare a type converter, in which case the text content is used as initialization text for that type converter. For example, Blue. This case is less common in practice.
The type must be a known XAML language primitive.
That is, the SolidColorBrush
class is able to route text content to its Color
property, by declaring “Color” as its content property.
Most likely the separate Color
class has an implicit cast from string
, allowing a valid string to be sent for any purpose that specifies a Color
.
2