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?
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 ).
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With