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

安稳与你 提交于 2020-01-12 18:51:10

问题


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?


回答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




回答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.



来源:https://stackoverflow.com/questions/651013/why-to-run-code-in-method-called-by-xaml-window-loaded

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!