Shahid Thaika
Shahid Thaika

Reputation: 2305

UWP - Run code once per page navigate

This is a simple question, but I still could not Google for a solution. What event in a C# UWP app runs only once per page navigation.

I added an event handler for back navigation right after:

this.InitializeComponent();

in the page constructor.

If I go back and forth the first and second page twice, it throws an error and debugging found that the event to handle back navigation was called twice, since the code in the page constructor also ran twice.

So in which event can I write code that I only want to run only once per page navigation. Or is there something similar to the below from ASP.net?

if (!Page.isPostback) {
   //do something
}

Upvotes: 0

Views: 832

Answers (2)

Shahid Thaika
Shahid Thaika

Reputation: 2305

Although I accepted another answer, in my specific situation the following code is better, cause it checks whether the back button handler is set or not.

    private void App_BackRequested(object sender, BackRequestedEventArgs e)
    {
        Frame rootFrame = Window.Current.Content as Frame;
        if (rootFrame == null)
            return;

        // If we can go back and the event has not already been handled, do so.
        if (rootFrame.CanGoBack && e.Handled == false)
        {
            e.Handled = true;
            rootFrame.GoBack();
        }
    }

Upvotes: 0

MrCSharp
MrCSharp

Reputation: 1143

There is a virtual method you can override on the page class: OnNavigatedTo which will be called by the framework when the page is finished loading and becomes the source of the parent frame.

https://learn.microsoft.com/en-us/uwp/api/windows.ui.xaml.controls.page.onnavigatedto#Windows_UI_Xaml_Controls_Page_OnNavigatedTo_Windows_UI_Xaml_Navigation_NavigationEventArgs_

Upvotes: 2

Related Questions