Tuesday, February 3, 2009

Silverlight: generic.xaml & OnApplyTemplate issues

In Silverlight, unlike WPF, the overriden OnApplyTemplate() method usually (but not always) gets called AFTER the Loaded event handler. This can be a source of many issues since you usually expect your control to fully load before handling the Loaded event. To prevent this behavior, you can call ApplyTemplate() within the body of the Loaded event handler, which will load the control template synchronously. What if it returns 'false' and your OnApplyTemplate doesn't get called at all?

You have created your custom control's class, put the style in Themes/generic.xaml resource dictionary, but you still keep getting the same XamlParserError exception on startup. Some investigation shows that your overriden OnApplyTemplate method never gets called. You try to invoke it manually by calling ApplyTemplate() in the Loaded event hander, but still no luck.

The solution is to fix your generic.xaml file - there is something wrong with it and neither Visual Studio nor Silverlight runtime will tell you what it is. Just comment the whole file out (except the style for your custom control, but comment out all its content) and you will see that now the OnApplyTemplate gets called.

Now begin uncommenting parts of the generic.xaml until you find what is causing the issue.

Labels: