2013-01-02 92 views
1

我有一個簡單的WPF應用程序與MainWindow。在後面的代碼中設置一個未加載的事件。將MainWindow設置爲啓動uri。當窗口關閉時,Unloaded不會被觸發。創建第二個窗口 - NotMainWindow只需點擊一下按鈕。奇怪的卸載行爲 - WPF窗口

在按鈕單擊事件中,調用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> 
+0

它在關閉時未被調用。這是問題。當然,它不會被稱爲加載! :P – Harsha

+0

@Blachshma - 更正了問題以消除混淆。 – Harsha

+0

所以你說你創建MainWindow,然後立即關閉它,卸載不被調用? – Blachshma

回答

3

根據你的意見,我明白你談論的場景。這是一個known issue,關閉應用程序時(例如,最後一個窗口關閉),不會調用卸載。

如果你只是想知道什麼時候窗口關閉使用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 
} 
+0

嗯。這看起來很合理。我的問題是,實際上,我需要在我正在構建的控件中的Unload事件,而不是窗口本身。控件可以託管在任何一種窗口中,但它不知道它的父控件。我需要在卸載控件時進行一些清理。 :| – Harsha

+0

接受任何可能需要此問題解決方案的人的答案。 :) – Harsha