Wpf Application.Current.MainWindow在启动事件处理程序中为空

Wpf Application.Current.MainWindow在启动事件处理程序中为空,wpf,Wpf,我在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

我在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”,意味着
应用程序.Current.main窗口
为空。如何在应用程序运行后立即访问主窗口实例?(即,我知道已触发此事件)

“如果在启动期间需要访问主窗口,则需要从启动事件处理程序手动创建新窗口对象。”-来源:

因此,在调用Application.Startup事件时,基本上您必须创建主窗口。您还可以从App.xaml中删除
StartupUri=“MainWindow”
,只需显示您创建的主窗口实例

App.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>
我希望这能回答您的问题。

“如果您需要在启动期间访问主窗口,则需要从启动事件处理程序手动创建新的窗口对象。”-来源:

因此,在调用Application.Startup事件时,基本上您必须创建主窗口。您还可以从App.xaml中删除
StartupUri=“MainWindow”
,只需显示您创建的主窗口实例

App.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>

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

非常感谢。我没有看到关于创建自己的窗口的说明。非常感谢。我没有看到关于创建自己的窗口的说明。