4. August 2011 21:54
See intro blogpost here.
Take a look at the following XAML:
<my:MyControl Loaded="MyControl_Loaded" />
Can you guess in what order the following events and methods will be triggered when the XAML loads:
- UserControl.Loaded event
- MyControl.Loaded event
- MyControl.OnApplyTemplate method
Come on... just guess...
The gotcha here is that it will be different for Silverlight and WPF!
Notice how OnApplyTemplate for the custom control fires before the Loaded events in WPF whereas in Silverlight if fires after. Therefore if you have code in OnApplyTemplate)() that relies on the the Loaded event having fired first, this probably won't work in WPF (nevermind the fact that your code is probably poorly designed if that's the case :-). Also note that the order the two loaded events fires are opposite.
This is also documented on MSDN:
“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”
A workaround for this is also suggested here: http://pagebrooks.com/archive/2008/11/30/tweaking-onapplytemplate-event-timing-in-silverlight-2.aspx
Next: WPF vs. Silverlight - Part 6 - Debug.WriteLine