Did You Know That… Type Converters allow you to use property attributes in Complex Types

There are two ways to add attributes to any element in Silverlight:

  1. property attribute syntax, which takes a string
  2. Property elements


Silverlight provides a number of built-in type converters to allow you to use the simpler property attribute syntax, where you might otherwise need to use a property element. The most familiar example of this is that you can write

<Rectangle Name="myRect0"

A naïve view of this code, might lead you to think that the stroke and fill colors are both strings.

You can quickly disabuse yourself of this notion by adding a little bit of code to your handleLoad event handler

handleLoad: function(plugIn, userContext, rootElement) 
    this.plugIn = plugIn;
    var myRect = plugIn.content.FindName("myRect0");
    alert("myRect.stroke = " + myRect.Stroke);
    alert("myRect.fill = " + myRect.Fill);

You might expect the first alert box to say "myRect.stroke = Black" and the second alert box to say "myRect.fill= Red"

But on reflection, you realize that what is in the stroke and in the fill is not a string, but rather is a solidColorBrush object that has been placed there using the typeConverter, as shown in figure 1




All of this makes a great deal more sense when you realize that the type converters are simply acting as shorthand, allowing you to avoid the more verbose but more explicit code, shown here


<Rectangle Name="myRect0"
        <SolidColorBrush Color="Black"  />

        <SolidColorBrush Color="Red" />

About Jesse Liberty

Jesse Liberty has three decades of experience writing and delivering software projects and is the author of 2 dozen books and a couple dozen Pluralsight & LinkedIn Learning courses. He was a Senior Technical Evangelist for Microsoft, a Distinguished Software Engineer for AT&T, a VP for Information Services for Citibank and a Software Architect for PBS. He is a Xamarin Certified Mobile Developer and a Xamarin MVP and a Microsoft MVP.
This entry was posted in z Silverlight Archives. Bookmark the permalink.