我有一个带有MainWindow的简单WPF应用程序。在后面的代码中设置一个卸载事件。将MainWindow设置为启动uri。当窗口关闭时不会触发卸载。创建第二个窗口-- NotMainWindow,只需单击一个按钮。
在单击事件按钮中,调用MainWindow。将触发关闭MainWindow并卸载。,为什么行为上的差异?我想要得到的是,我如何在每次中都得到某种卸载的事件?
<Window x:Class="WpfApplication2.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" Unloaded="Main_Unloaded">
<Grid>
</Grid>
</Window>
    private void Main_Unloaded(object sender, RoutedEventArgs e)
    {
    }
<Window x:Class="WpfApplication2.NotMainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="NotMainWindow" Height="300" Width="300">
<Grid>
    <Button Content="Show Main" Height="25" Margin="10" Width="70" Click="Button_Click" />
</Grid>
</Window>
private void Button_Click(object sender, RoutedEventArgs e)
    {
        MainWindow win = new MainWindow();
        win.Show();
    }
<Application x:Class="WpfApplication2.App"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         StartupUri="NotMainWindow.xaml">
<Application.Resources>
</Application.Resources>
</Application>发布于 2013-01-02 10:12:33
基于你的评论,我理解你所说的情景。这是一个在关闭应用程序时不调用卸载的已知问题 (例如,关闭最后一个窗口)。
如果您只想知道窗口何时关闭,请使用Closing事件:
public MainWindow()
{
    this.Closing += new CancelEventHandler(MainWindow_Closing);
    InitializeComponent();
}
void MainWindow_Closing(object sender, CancelEventArgs e)
{
   // Closing logic here.
}如果您想知道最后一个窗口何时关闭,例如您的应用程序正在关闭,则应该使用ShutdownStarted
public MainWindow()
{
    this.Dispatcher.ShutdownStarted += Dispatcher_ShutdownStarted;
    InitializeComponent();
}
private void Dispatcher_ShutdownStarted( object sender, EventArgs e )
{
   //do what you want to do on app shutdown
}https://stackoverflow.com/questions/14119939
复制相似问题