#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.

Advertisement

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

One Response to #609 – Perform Initialization in Window.Loaded Handler

  1. Pingback: Dew Drop – July 24, 2012 (#1,370) | Alvin Ashcraft's Morning Dew

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: