#87 – Type Converters
October 7, 2010 1 Comment
In XAML, you often set a property value by specifying a single string value. However, when setting the value of a property that is not a System.String, the specified string must be converted into the proper type. This is done automatically by the XAML parser using a type converter.
For example, in the example below, we set the background color of a button by specifying the string “Azure”.
<Button Content="Click Me" Background="Azure" Height="25" Width="50" />
Because the Button.Background property is of type System.Windows.Media.Brush, the parser must convert the string “Azure” to a Brush object.
The XAML parser will attempt to convert the value if either:
- The property in question has a TypeConverter attribute
- The class that implements the property’s type has a TypeConverter attribute
For the Button.Background property, the value is converted from a string to a SolidColorBrush by the System.Windows.Media.BrushConverter class.
Pingback: #209 – Specifying a Color Where a Brush Is Expected in XAML « 2,000 Things You Should Know About WPF