#609 – Perform Initialization in Window.Loaded Handler

Quite often you will want to perform some sort of initialization when your application first starts up.  You could add code to do this in the constructor for your main Window object.  For example:

<StackPanel>
    <Label Name="lblToday" Content="Today is XXX"/>
</StackPanel>

 

        public MainWindow()
        {
            this.InitializeComponent();

            lblToday.Content = string.Format("Today is {0}", DateTime.Now.ToShortDateString());
        }

A better method, however, is to do this initialization in a handler for the Window.Loaded event.

        public MainWindow()
        {
            this.InitializeComponent();

            this.Loaded += new RoutedEventHandler(MainWindow_Loaded);
        }

        void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {
            lblToday.Content = string.Format("Today is {0}", DateTime.Now.ToShortDateString());
        }

An exception that originates from the window’s constructor will be thrown as a XamlParseException (with the original exception in the InnerException). If, however, the exception originates from an event handler, it will not be wrapped in another exception.

Advertisements