在 App.xaml.cs 的启动时关闭第一个窗口后打开 C# WPF 第二个窗口



我有2个WPF窗口。App.xaml.cs 打开第一个窗口并在显示状态的同时读取一些数据,然后关闭它。然后 App.xaml.cs 打开第二个窗口。当我调试代码正确执行时,但在关闭第一个窗口后,它会关闭整个应用程序。我做错了什么?在 App.xaml 中不可能吗.cs ?

这是代码。(对于此测试,我使用代码隐藏而不是 MVVM)在此代码中,我放置了一个按钮来关闭第一个窗口。

App.xaml.cs:

public partial class App : Application
{
    protected override void OnStartup(StartupEventArgs e)
    {
        base.OnStartup(e);
        TestWindow tw = new TestWindow();
        bool? rslt = tw.ShowDialog();
        if (rslt == true) 
        {
            MainWindow mw = new MainWindow();
            mw.Show(); //I am not sure why the Application close itself 
        }
    }
}

TestWindow.xaml:

<Window x:Class="Shell.Startup.TestWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="TestWindow" Height="300" Width="300">
    <Grid>
        <Button x:Name="ButtonYes" Content="Yes" HorizontalAlignment="Left" Height="21" Margin="95,192,0,0" VerticalAlignment="Top" Width="66" RenderTransformOrigin="1.485,0.81" Click="ButtonYes_Click"/>
    </Grid>
</Window>

TestWindow.xaml.cs:

public partial class TestWindow : Window
{
    public TestWindow()
    {
        InitializeComponent();
    }
    private void ButtonYes_Click(object sender, RoutedEventArgs e)
    {
        DialogResult = true;
        Close();
    }
}

MainWindow.xaml:

<Window x:Class=" Shell.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525">
    <Grid>
    </Grid>
</Window>

注意:

我也尝试了这里答案中给出的Application_Startup。

更改 App.xaml 中的应用程序关闭模式,如下所示。注意 ShutdownMode="OnExplicitShutdown"

<Application x:Class="WpfApplication2.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             ShutdownMode="OnExplicitShutdown">
    <Application.Resources>
    </Application.Resources>
</Application>

那么应用程序类中的启动方法应该是

    protected override void OnStartup(StartupEventArgs e)
    {
        base.OnStartup(e);
        TestWindow t = new TestWindow();
        bool? res = t.ShowDialog();
        if (res == true)
        {
            MainWindow mw = new MainWindow();
            mw.Show();
        }
        else
            this.Shutdown();
    }

最后,我们必须显式关闭应用程序,因为我们更改了关闭模式。因此,您的主窗口应具有以下代码

/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        this.Closed += MainWindow_Closed;
    }
    void MainWindow_Closed(object sender, EventArgs e)
    {
        App.Current.Shutdown();
    }
}

最新更新