Search code examples
c#uwpnavigationinitializationback-button

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
}

Solution

  • 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_