为什么要在 XAML Window.Loaded 调用的方法中运行代码? [英] Why to run code in method called by XAML Window.Loaded?

查看:38
本文介绍了为什么要在 XAML Window.Loaded 调用的方法中运行代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到了一个代码示例,它创建了一个方法 Window_Loaded(),该方法由 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>

但是在后面的代码中,代码在构造函数和Window_Loaded()方法中都有效:

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? 
        }
    }
}

这样做有什么好处吗?

是否有像 ASP.NET 中的窗口加载周期"这样的有助于了解的方法,即 PreRender()PostRender() 等方法> 等?

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?

推荐答案

是的,WPF 控件也有类似的生命周期,就像在 ASP.NET 中一样.不过,WPF 控件的生命周期更简单,因为它基本上由初始化、加载和卸载事件(按此顺序)组成.见:

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

Mike Hillberg 有一篇很棒的文章展示了初始化事件和加载事件之间的区别:

and Mike Hillberg has an excellent article demonstrating the difference between the initalized and loaded events:

http://blogs.msdn.com/mikehillberg/存档/2006/09/19/LoadedVsInitialized.aspx

这篇关于为什么要在 XAML Window.Loaded 调用的方法中运行代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆