Why to run code in method called by XAML Window.Loaded?

13,534

Solution 1

Yes, there is a similar life cycle for WPF controls, just like in ASP.NET. The life cycle of WPF controls is simpler though, as it basically consits of an initialized, loaded, and unloaded event (in that order). See:

http://msdn.microsoft.com/en-us/library/ms754221.aspx

and Mike Hillberg has an excellent article demonstrating the difference between the initalized and loaded events:

http://blogs.msdn.com/mikehillberg/archive/2006/09/19/LoadedVsInitialized.aspx

Solution 2

Excellent links, Razzie.

Edward - you'll find that the most interresting distinction is that the Contructor as always the first method called on your Window/Page/UserControl and you can't count on all DependencyProperties having been initialized to their final values. Also, it's ill advised to call any virtual methods from within your construtructor.

The Loaded event, by contrast, is generally called at the end of the initialization processes... that is - when the Window/Page/UserControl has been fully loaded into a WPF ElementTree. From within your loaded event, you can confidently call any methods and modify any DepenencyProperty without risk of unexpected results.

A nice pattern (which I'm currently using in my project) is to initialize custom dependency properties in the Loaded event if they haven't been modified during initialization. For controls, this pattern allows you to avoid initializing "expensive" properties (like a DependencyProperty which is an ObservableCollection) if they are being overwritten (i.e. by a property Binding from the calling code).

Simple answer: Use the Loaded event if you're not sure about how to safely overload the constructor.

Share:
13,534
Angry Dan
Author by

Angry Dan

web/software developer, .NET, C#, WPF, PHP, software trainer, English teacher, have philosophy degree, love languages, run marathons my tweets: http://www.twitter.com/edward_tanguay my runs: http://www.tanguay.info/run my code: http://www.tanguay.info/web my publications: PHP 5.3 training video (8 hours, video2brain) my projects: http://www.tanguay.info

Updated on June 04, 2022

Comments

  • Angry Dan
    Angry Dan almost 2 years

    I saw a code example that creates a method Window_Loaded() which is called by XAML's "Window Loaded" event:

    <Window x:Class="TestModuleLoader.Window1"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Window1" Height="300" Width="300" Loaded="Window_Loaded">
        <Grid>
            ...
        </Grid>
    </Window>
    

    But in the code behind, the code worked in both the constructor and the Window_Loaded() method:

    using System.Windows;
    
    namespace TestModuleLoader
    {
        public partial class Window1 : Window
        {
            public Window1()
            {
                InitializeComponent();
            }
    
            private void Window_Loaded(object sender, RoutedEventArgs e)
            {
                //what advantages do I have running code here? 
            }
        }
    }
    

    Are there any advantages to doing this?

    Is there a "Window Load Cycle" as in ASP.NET going on here that is helpful to know about, i.e. methods such as PreRender(), PostRender(), etc?

  • Angry Dan
    Angry Dan about 15 years
    Mike Hillberg says in his blog "if you're not sure which event to use, and you don't want to read any more, use the Loaded event". Excellent, I'm feeling a little overloaded with WPF at the moment and that's all I need to know for now. Thanks for the link!