我看到很多人在App.xaml.cs内使用“ base.OnStartup(e)”:
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
MaiWindow app = new MainWindow();
app.Show();
}
有需要吗?它的目的是什么?
答案 0 :(得分:1)
它允许任何基类逻辑运行;就像p1
的其他用法一样。
可能严格不是必需的;但在覆盖total
方法时调用基类的实现被认为是最佳实践(除非您积极地想抑制基行为)。
答案 1 :(得分:0)
.NET Framework代码可在https://referencesource.microsoft.com
上找到Application.OnStartup()没有太多功能:
/// <summary>
/// OnStartup is called to raise the Startup event. The developer will typically override this method
/// if they want to take action at startup time ( or they may choose to attach an event).
/// This method will be called once when the application begins, once that application's Run() method
/// has been called.
/// </summary>
/// <param name="e">The event args that will be passed to the Startup event</param>
protected virtual void OnStartup(StartupEventArgs e)
{
// Verifies that the calling thread has access to this object.
VerifyAccess();
StartupEventHandler handler = (StartupEventHandler)Events[EVENT_STARTUP];
if (handler != null)
{
handler(this, e);
}
}
我们可以向Startup事件添加处理程序,而不是覆盖OnStartup():
<Application x:Class="WpfApp.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Startup="LaunchWpfApp">
private void LaunchWpfApp(object sender, StartupEventArgs e)
{
MaiWindow app = new MainWindow();
app.Show();
}