我有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>
注:的
我还尝试了答案here中给出的Application_Startup。
答案 0 :(得分:4)
在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>
然后你的App类中的onStartup方法应该是
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();
}
最后我们必须明确关闭应用程序,因为我们将关闭模式更改为是。因此,您的MainWindow应具有以下代码
/// <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();
}
}