Silverlight 2.0 offers the possibility to use styles and templates on controls. It works almost the same as it does for WPF, except for a few minor things that might give developers a major headache when you don’t know what to look for.
One of the things that you need to know is that the errorhandling in silverlight isn’t exactly as good as it is for WPF. It is not even as good as the error handling for WPF 3.0 (The first version of WPF). At least that version gave you an error saying that the syntax of the XAML was wrong. Silverlight 2.0 just throws random exceptions that don’t really tell you what is going wrong.
When working with custom styles you can create a style like this:
1: <Style x:Key="MyInvalidStyle">
2: <Setter Property="Background" Value="Red"/>
3: </Style>
This will give you a very nice ExecutionEngineException. I was kind of puzzled by the fact that the whole runtime was going down the drain on that piece of XAML, because the error is easily catched and can be handled in a much more user-friendly way. What the runtime is trying to tell you, is that you forgot to add the TargetType attribute to the style. So if you do that, you will end up with the following example:
1: <Style x:Key="MyInvalidStyle" TargetType="StackPanel">
2: <Setter Property="Background" Value="Red"/>
3: </Style>
I really, really hope Microsoft adds better errorhandling to silverlight 3.0, because this isn’t the only error that is unexplainable when you just look at the errormessage. Depending on where you define the style, you can also get a AG_E_UNKNOWN_ERROR javascript error. This is another way of telling you that silverlight was unable to load the style or the controltemplate you created. However, it might just as well be something else that causes the runtime to go into epic fail mode 😉
So the tip of the day is: Check your XAML when the runtime of silverlight fails to load properly and raises the ExecutionEngineException or gives an AG_E_UNKNOWN_ERROR javascript error.