#87 – Type Converters

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.


About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

One Response to #87 – Type Converters

  1. Pingback: #209 – Specifying a Color Where a Brush Is Expected in XAML « 2,000 Things You Should Know About WPF

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: