Home > Articles > Programming > C#

Mastering XAML

  • Print
  • + Share This
This chapter is from the book

Type Converters

Let’s look at the C# code equivalent to the preceding Button declaration that sets both Content and Background properties:

Windows.UI.Xaml.Controls.Button b = new Windows.UI.Xaml.Controls.Button();
b.Content = "Stop";
b.Background = new Windows.UI.Xaml.Media.SolidColorBrush(Windows.UI.Color.Red);

Wait a minute. How can "Red" in the previous XAML file be equivalent to the SolidColorBrush instance used in the C# code? Indeed, this example exposes a subtlety with using strings to set properties in XAML that are a different data type than System.String or System.Object. In such cases, the XAML parser must look for a type converter that knows how to convert the string representation to the desired data type.

You cannot currently create your own type converters, but type converters already exist for many common data types. Unlike the XAML language, these type converters support case-insensitive strings. Without a type converter for Brush (the base class of SolidColorBrush), you would have to use property element syntax to set the Background in XAML as follows:

<Button xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    <SolidColorBrush Color="Red"/>

And even that is only possible because of a type converter for Color that can make sense of the "Red" string. If there wasn’t a Color type converter, you would basically be stuck. Type converters don’t just enhance the readability of XAML; they also enable values to be expressed that couldn’t otherwise be expressed.

Unlike in the previous C# code, in this case, misspelling Red would not cause a compilation error but would cause an exception at runtime. (Although Visual Studio does provide compile-time warnings for mistakes in XAML such as this.)

  • + Share This
  • 🔖 Save To Your Account