C# WPF中是否存在form.onload?
我想在WPF中加载表单时运行一些代码。有可能这样做吗?我无法找到在哪里为表单onload编写代码C# WPF中是否存在form.onload?,c#,wpf,C#,Wpf,我想在WPF中加载表单时运行一些代码。有可能这样做吗?我无法找到在哪里为表单onload编写代码 从下面的回答来看,我所问的似乎不是WPF中通常做的事情?在Vb.NETWinForms中,这很简单,只需转到onload事件并添加需要在加载时运行的代码。无论出于何种原因,在C#WPF中,这似乎非常困难,或者说没有标准的方法来做到这一点。有人能告诉我最好的方法是什么吗?您可以订阅窗口的事件并在事件处理程序中执行您的工作: public MyWindow() { Loaded += MyWindo
从下面的回答来看,我所问的似乎不是WPF中通常做的事情?在Vb.NETWinForms中,这很简单,只需转到onload事件并添加需要在加载时运行的代码。无论出于何种原因,在C#WPF中,这似乎非常困难,或者说没有标准的方法来做到这一点。有人能告诉我最好的方法是什么吗?您可以订阅窗口的事件并在事件处理程序中执行您的工作:
public MyWindow()
{
Loaded += MyWindow_Loaded;
}
private void MyWindow_Loaded(object sender, RoutedEventArgs e)
{
// do work here
}
或者,根据您的场景,您可以在中完成工作。有关二者之间差异的讨论,请参阅加载的事件文档。使用窗口的加载事件。您可以在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">
这个问题是4年前提出的,但这个答案也可能对其他人有所帮助,因此--> 要简单快速地完成这项工作,请将要在方法中运行的代码放在代码后面。然后只需在
MainWindow()初始化组件()之前调用该方法即可。这会带来危险,但大多数情况下都会起作用,因为组件是在窗口启动/显示之前加载的。
(这是我的一个项目中的工作代码。)
假设你想在应用程序启动时播放一个短波文件。它看起来像这样
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();
}
}
}
希望这对正在搜索的用户有所帮助。:-) 已加载
事件在项目生成后引发。要在之前完成这些工作,您可以在App.xaml.cs
中验证启动时的方法
public partial class App : Application
{
protected override void OnStartup(StartupEventArgs e)
{
//...
base.OnStartup(e);
}
}
您是否可以用表单的New()methid编写代码?为什么要在构造函数中而不是在XAML中订阅事件?因为对我来说,这是代码的逻辑部分——行为,而不是视图(这是一种解决缺少虚拟加载方法的方法)。例如,如果我必须将XAML交给图形设计师在Blend中编辑,我希望他们不能修改加载的事件处理。不过,这是一个无关紧要的决定!这比另一个解决方案更适合我。谢谢非常感谢你!!
public partial class App : Application
{
protected override void OnStartup(StartupEventArgs e)
{
//...
base.OnStartup(e);
}
}