1

MainWindowを備えた単純なWPFアプリケーションがあります。コードビハインドでアンロードイベントを設定します。MainWindowを起動uriとして設定します。ウィンドウを閉じても、アンロードはトリガーされません。NotMainWindowボタンを1回クリックするだけで、2番目のウィンドウを作成します。

ボタンクリックイベントで、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>
4

1 に答える 1

3

あなたのコメントに基づいて、私はあなたが話しているシナリオを理解しています。これは、アプリケーションをシャットダウンするときにアンロードが呼び出されないという既知の問題です(たとえば、最後のウィンドウが閉じられます)。

ウィンドウがいつ閉じられるかを知りたいだけの場合は、次の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
}
于 2013-01-02T10:12:33.323 に答える