Type converters are one of the coolest and one of the most usefull features of XAML (Extensible Application Markup Language). They do not only speed up the development process and make the code much more readable. They also enable many other XAML features that would be impossible to accomplish otherwise.

 

Let`s begin with simple example to demonstrate the idea that stands behind type converters. Suppose we have a simple grid container:

 

<Grid Height="300" Width="300">       

</Grid>

 

If we would be to change its background color, then it`s  enough to add the following attribute:

 

<Grid Height="300" Width="300" Background="RoyalBlue">       

</Grid>

 

Cool. But wait! Isn`t a Background property of type Brush? So why assigning a string for a property of type Brush works? Because a Brush type converter exists. Its role is to take a string as an argument and to try to convert it to the desired data type.

 

The given code snippet could be rewritten in the following way:

 

<Grid Height="300" Width="300">

<Grid.Background>

            RoyalBlue

      </Grid.Background>       

</Grid>

 

But that is simply the same. However the next snippet is more interesting:

 

<Grid Height="300" Width="300">

<Grid.Background>

            <SolidColorBrush Color="RoyalBlue"></SolidColorBrush>

      </Grid.Background>       

</Grid>

 

Now any Brush type converter is not needed at all. In fact we have defined our own object of type Brush (SolidColorBrush class derives from Brush), so we don`t need any special magic to assign it for a Brush-type property of a grid. However SolidColorBrush has a Color property, which is of type Color. So we need another type converter to convert our string “RoyalBlue” to the object of type color.

 

We can continue moving into this direction and try to avoid using Color type converter as well. This is easily possible:

<Grid Height="300" Width="300">

<Grid.Background>

            <SolidColorBrush>

                  <SolidColorBrush.Color>

                        <Color R="41" G="69" B="225" A="255"></Color>

                  </SolidColorBrush.Color>

            </SolidColorBrush>

</Grid.Background>       

</Grid>

 

Although we have successfully avoided usage of Color type converer, the int type converter is necessary in this case. And unlike in previous examples, it is impossible to avoid it.

 

So this brought us to an interesting conclusion. XAML would be useless without type converters. Hardly anything could be declared in XAML and developers would be doomed to design their user interfaces in procedural code without any designer support.