#GIS from a .NET developer's perspective

WPF vs. Silverlight - Part 5 - XAML Control Instantiation

See intro blogpost here.

Take a look at the following XAML:

    <UserControl Loaded="UserControl_Loaded">
        <my:MyControl Loaded="MyControl_Loaded" />

Can you guess in what order the following events and methods will be triggered when the XAML loads:

    - UserControl.Constructor
    - MyControl.Constructor
    - 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!

Silverlight WPF
UserControl.Constructor UserControl.Constructor
MyControl.Constructor MyControl.Constructor
MyControl.Loaded event MyControl.OnApplyTemplate method
UserControl.Loaded event UserControl.Loaded event
MyControl.OnApplyTemplate method MyControl.Loaded event

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:

Next: WPF vs. Silverlight - Part 6 - Debug.WriteLine

Pingbacks and trackbacks (1)+

Comments are closed