Tweaking OnApplyTemplate Event Timing in Silverlight 2

When building a custom control in Silverlight 2, the OnApplyTemplate method gives you the opportunity to “wire-up” logical instances of elements in your control.  When a control is loaded, it is important to realize that in Silverlight 2, this method is not triggered very early with respect to other events.  In other words, you could very easily write code that fails just because of where you call it.  Understanding the control’s life cycle will help in avoiding these situations.

At the time this was written, the MSDN documentation stated:

“The timing of the Loaded event in Silverlight differs from the timing of the FrameworkElement.Loaded event in WPF. Specifically, the WPF Loaded event occurs after the template is applied. In Silverlight, the Loaded event is not guaranteed to occur after the template is applied.”

After running a quick test, it is easy to see that this is true.  My simple test shows that the OnApplyTemplate call fired after both the Control’s Loaded Event and the Page Loaded event.

image

Note: Dave Relyea has a very comprehensive post with a table outlining the control lifecycle which confirms my test :-)

Without too much trouble, you can force the OnApplyTemplate call to fire and consequently change the order of events with a simple work-around:

public class MyControl : Control 
{
public MyControl()
{
this.DefaultStyleKey = typeof(MyControl);
this.Loaded += new RoutedEventHandler(MyControl_Loaded);
}

void MyControl_Loaded(object sender, RoutedEventArgs e)
{
this.ApplyTemplate(); // Synchronous call ...
}

public
override void OnApplyTemplate()
{
...
}
...

By calling ApplyTemplate in the Loaded event handler, we effectively change the event order to the following:

image

Now, any code in the Control or Page Loaded event handlers that is dependent upon the template being applied will fire correctly.


Feedback

# re: Tweaking OnApplyTemplate Event Timing in Silverlight 2

Gravatar It was helpfull to understand the control’s life cycle. It was not so ease in the first moment. Thanks 12/1/2008 1:26 AM | Silverlight Travel

# re: Tweaking OnApplyTemplate Event Timing in Silverlight 2

Gravatar Glad I could help! 12/1/2008 8:16 AM | pbrooks

Comments have been closed on this topic.