WPF中存在form.onload吗?

63

我希望在WPF表单加载时运行一些代码。这是否可行?我找不到在表单加载时编写代码的位置。

根据下面的回复,似乎在WPF中通常不会做我所要求的事情?在Vb.Net winforms中很容易,只需转到 onload 事件并添加所需的代码即可在加载时运行。由于某种原因,在C# WPF中似乎非常困难或没有标准方法来实现这一点。请问有谁能告诉我最好的方法是什么?


你的代码不会在表单的New()方法中工作吗? - Michael Rodrigues
请点击此处查看相关的编程内容:http://msdn.microsoft.com/zh-cn/library/ms742302.aspx - RajeshKdev
4个回答

108

您可以订阅 Window 的 Loaded 事件,并在事件处理程序中执行您的工作:

public MyWindow()
{
  Loaded += MyWindow_Loaded;
}

private void MyWindow_Loaded(object sender, RoutedEventArgs e)
{
  // do work here
}

或者,根据你的情况,你可能可以在 OnInitialized 中完成你的工作。请参阅Loaded事件文档,了解两者之间的区别。


为什么你在构造函数中订阅事件而不是在XAML中订阅? - Taylor Leese
21
因为这对我来说在逻辑上是代码行为的一部分,而不是视图(它是缺少虚拟OnLoaded方法的变通方法)。例如,如果我需要将XAML交给平面设计师在Blend中进行编辑,我希望他们不能修改Loaded事件处理。不过,这是一个边缘情况! - itowlson

36

使用窗口的Loaded事件。您可以在XAML中进行如下配置:

<Window x:Class="WpfTest.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Your App" Loaded="Window_Loaded">

这是Window_Loaded事件的示例:

private void Window_Loaded(object sender, RoutedEventArgs e)
{
    // do stuff
}

2

这个问题是4年前问的,但这个答案可能也会对其他人有帮助,所以我来回答一下 - > 简单快速地实现 - 粗暴地把你想要运行的代码放在代码后台的一个方法中,然后在MainWindow() InitializeComponent()之前直接调用这个方法。虽然存在危险性,但大多数情况下它能够工作,因为组件在窗口初始化/显示之前已经加载好了。 (这是我其中一个项目的可用代码示例。) 假设你想让应用程序启动时播放一个短音频文件,代码如下;

using ...
using System.Windows.Media;

namespace yourNamespace_Name
{
    /// sumary >
    /// Interaction logic for MainWindow.xaml
    /// /sumary>
    public partial class MainWindow : System.Windows.Window
    {
        public MainWindow()
        {
            /*call your pre-written method w/ all the code you  wish to
             * run on project load. It is wise to set the method access
             * modifier to 'private' so as to minimize security risks.*/
            playTada();

            InitializeComponent();
        }

        private void playTada()
        {
            var player = new System.Media.SoundPlayer();
            player.Stream = Properties.Resources.tada;
            // add the waveFile to resources, the easiest way is to copy the file to
            // the desktop, resize the IDE window so the file is visible, right 
            // click the Project in the solution explorer & select properties, click
            // the resources tab, & drag and drop the wave file into the resources 
            // window. Then just reference it in the method.
            // for example: "player.Stream = Properties.Resources.tada;"         
            player.Play();
            //add garbage collection before initialization of main window
            GC.Collect();
            GC.WaitForPendingFinalizers();
        }
    }
}

希望这可以帮助那些正在寻找的人。 :-)

-1

Loaded事件在项目构建完成后被触发。如果想要在此之前进行操作,可以在App.xaml.cs中重写OnStartup方法。

public partial class App : Application
{
    protected override void OnStartup(StartupEventArgs e)
    {
        //...
        base.OnStartup(e);
    }
}  

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接