Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 295
Edward Tanguay Avatar asked Mar 16 '09 15:03

Edward Tanguay


People also ask

What is loaded in WPF?

In general, in WPF the Loaded event fires if the element: is laid out, rendered, and ready for interaction. Since in WPF the Window is the same element, but it should be generally content that is arranged in a root panel (for example: Grid ).

What is the difference between a page and a window in WPF when you are adding a new file in the Solution Explorer?

Window is the root control that must be used to hold/host other controls (e.g. Button) as container. Page is a control which can be hosted in other container controls like NavigationWindow or Frame. Page control has its own goal to serve like other controls (e.g. Button). Page is to create browser like applications.

Why XAML is used in WPF?

The goal of XAML is to enable visual designers to create user interface elements directly. WPF aims to make it possible to control all visual aspects of the user interface from mark-up.

What is the difference between XAML and WPF?

In 2006, WPF was released which is an alternative to WinForms. WPF uses XAML, which is a language based on XML, to declare the user interface elements. In a simple WPF app, the . xaml file describes the GUI and the code-behind file describes the logic.


1 Answers

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

like image 173
Razzie Avatar answered Sep 20 '22 20:09

Razzie