gpt4 book ai didi

wpf - Application.Current.MainWindow 在启动事件处理程序中为 null

转载 作者:行者123 更新时间:2023-12-05 09:22:24 49 4
gpt4 key购买 nike

我在 Windows 窗体方面有很强的背景,并且我开始在 WPF 中工作。考虑我后面的应用程序代码中的以下事件处理程序:

Private Sub Application_Startup(ByVal sender As Object, ByVal e As System.Windows.StartupEventArgs) Handles Me.Startup
Debug.Print(Application.Current.MainWindow Is Nothing)
End Sub

这会打印“True”,表示 Application.Current.MainWindow 为空。如何在应用程序运行后立即访问主窗口实例? (即我知道这个事件被触发了 as soon as the application is run )

最佳答案

“如果您需要在启动期间访问主窗口,则需要从您的启动事件处理程序手动创建一个新的窗口对象。” - 来源:http://msdn.microsoft.com/en-us/library/system.windows.application.startup(v=vs.110).aspx

所以基本上您必须在调用 Application.Startup 事件时创建主窗口。您也可以从您的 App.xaml 中删除 StartupUri="MainWindow" 并仅显示您创建的主窗口的实例。

应用.xaml

<Application x:Class="Namespace.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
StartupUri="MainWindow.xaml" <---- Remove this
Startup="Application_Startup"
>
<Application.Resources>

</Application.Resources>
</Application>

App.xaml.cs

private void Application_Startup(object sender, StartupEventArgs e)
{
MainWindow wnd = new MainWindow();
wnd.Show();
}

我希望这能回答您的问题。

关于wpf - Application.Current.MainWindow 在启动事件处理程序中为 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26720810/

49 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com