WPF中是否存在form.onload?

我想在WPF中运行一个窗体的代码。 是否有可能做到这一点? 我无法find在哪里编写onload的代码。

从下面的回答来看,似乎我所要求的并不是通常在WPF中所做的事情? 在Vb.Net的winforms很容易,你只要去onload事件,并添加你需要加载运行的代码。 无论出于何种原因,在C#WPF中看起来非常困难,或者没有标准的方法来做到这一点。 有人可以告诉我什么是这样做的最好方法?

您可以订阅Window's Loaded事件,并在事件处理程序中完成您的工作:

public MyWindow() { Loaded += MyWindow_Loaded; } private void MyWindow_Loaded(object sender, RoutedEventArgs e) { // do work here } 

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

使用窗口的Loaded事件。 你可以像下面这样在XAML中configuration它:

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

项目Loaded后引发Loaded事件。 要做之前的事情,你可以在App.xaml.cs OnStartup方法。

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

这个问题在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(); } } } 

希望这有助于那些正在search。 🙂