我希望在WPF表单加载时运行一些代码。这是否可行?我找不到在表单加载时编写代码的位置。
根据下面的回复,似乎在WPF中通常不会做我所要求的事情?在Vb.Net winforms中很容易,只需转到 onload 事件并添加所需的代码即可在加载时运行。由于某种原因,在C# WPF中似乎非常困难或没有标准方法来实现这一点。请问有谁能告诉我最好的方法是什么?
我希望在WPF表单加载时运行一些代码。这是否可行?我找不到在表单加载时编写代码的位置。
根据下面的回复,似乎在WPF中通常不会做我所要求的事情?在Vb.Net winforms中很容易,只需转到 onload 事件并添加所需的代码即可在加载时运行。由于某种原因,在C# WPF中似乎非常困难或没有标准方法来实现这一点。请问有谁能告诉我最好的方法是什么?
您可以订阅 Window 的 Loaded 事件,并在事件处理程序中执行您的工作:
public MyWindow()
{
Loaded += MyWindow_Loaded;
}
private void MyWindow_Loaded(object sender, RoutedEventArgs e)
{
// do work here
}
或者,根据你的情况,你可能可以在 OnInitialized 中完成你的工作。请参阅Loaded事件文档,了解两者之间的区别。
使用窗口的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
}
这个问题是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();
}
}
}
Loaded
事件在项目构建完成后被触发。如果想要在此之前进行操作,可以在App.xaml.cs
中重写OnStartup
方法。
public partial class App : Application
{
protected override void OnStartup(StartupEventArgs e)
{
//...
base.OnStartup(e);
}
}