0

My app has multiple pages. When I press the Close key in the toolbar, how can I detect the OnClosing event in the single page to avoid closing the app instead of going back to the MainWindow with "this.Frame.GoBack();" ?

I can only catch OnClosing on MainWindow

Daniel A. White
  • 187,200
  • 47
  • 362
  • 445

2 Answers2

0

You can use the Unloaded event on Pages.

*.xaml

<local:TestPage Unloaded="TestPage_Unloaded" />

*.xaml.cs

private void TestPage_Unloaded(object sender, RoutedEventArgs e)
{
    // Do your page closing work here...
}
Andrew KeepCoding
  • 7,040
  • 2
  • 14
  • 21
0

You could store a reference to the window in a property or field in your App.xaml.cs class as suggested here and then handle the Closing event of the window in the Page class something like this:

public sealed partial class MainPage : Page
{
    private Window _parentWindow;

    public MainPage()
    {
        this.InitializeComponent();
        this.Loaded += OnLoaded;
        this.Unloaded += OnUnloaded;
    }

    private void OnLoaded(object sender, RoutedEventArgs e)
    {
        _parentWindow = (Application.Current as App)?.m_window;
        if (_parentWindow != null)
            _parentWindow.Closed += OnWindowClosed;
    }

    private void OnUnloaded(object sender, RoutedEventArgs e)
    {
        if (_parentWindow != null)
            _parentWindow.Closed -= OnWindowClosed;
    }

    private void OnWindowClosed(object sender, WindowEventArgs args)
    {
        // Prevent the window from being closed based on some logic of yours...
        args.Handled = true;
    }
}
mm8
  • 163,881
  • 10
  • 57
  • 88