Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the Closing event in UWP Page?

In WPF, there is a Closing event on <Window... tag, where we can hook up some dispose code in MainWindow_OnClosing.

But there is no such event in UWP app. The closing I guess is Unloaded, not even Unloading is there.

I just placed my disposing code there but still feel concerned. Is Unloaded event supposed for this type of work? Is there something I need to take note?

like image 490
Blaise Avatar asked Jun 16 '16 14:06

Blaise


Video Answer


1 Answers

According to the MSDN, the Window class has a Closed event. I'm mentioning this as you posted the Closing event of a window component, but keep in mind the remark of the event:

The Closed event occurs when a Window closes. However, Windows Store apps typically use a single Window instance, and do not open and close additional Window instances.

Now, when using the Frame navigation system of the main window with Pages, I advise you to use the OnNavigatedTo and OnNavigatedFrom events to manipulate all initialisation and dispose functionality of the class.

You may want to pay attention to the OnNavigationFrom as it is invoked immediately before the Page is unloaded and is no longer the current source of a parent Frame.

A really simple example:

Windows.ApplicationModel.Resources.ResourceLoader loader;

protected override void OnNavigatedTo(NavigationEventArgs e)
{
    base.OnNavigatedTo(e);

    loader = new Windows.ApplicationModel.Resources.ResourceLoader();
    var navigationPageContentFormat = loader.GetString("NavigationPageContent");
    var navigationPageContentWhenEmpty = loader.GetString("NavigationPageContentWhenEmpty");

    this.ParameterTextBlock.Text = String.Format(navigationPageContentFormat, e.Parameter?.ToString() ?? navigationPageContentWhenEmpty);
}

protected override void OnNavigatingFrom(NavigatingCancelEventArgs e)
{
    loader = null;
}
like image 187
Nahuel Ianni Avatar answered Sep 17 '22 03:09

Nahuel Ianni