miskohut
miskohut

Reputation: 1017

UWP - Proper way of passing parameters between pages

Suppose I want to pass one object (reference) through several pages. I can navigate and pass parameters via Frame.Navigate(typeof(FirstPage), object). But how to pass the reference back on back press properly?

protected override void OnNavigatedTo(NavigationEventArgs e) {
   if (e.Parameter is SomeClass) {
      this.someObject = (SomeClass)e.Parameter;
   }
   else {
      this.someObject = new SomeClass();
   }

   SystemNavigationManager.GetForCurrentView().AppViewBackButtonVisibility = AppViewBackButtonVisibility.Visible;
   SystemNavigationManager.GetForCurrentView().BackRequested += OnHardwareButtonsBackPressed;

   base.OnNavigatedTo(e);
}


private void OnHardwareButtonsBackPressed(object sender, BackRequestedEventArgs e) {
   // This is the missing line!
   Frame.Navigate(typeof(FirstPage), this.someObject);
}

But when I press back button it goes back to the FirstPage OnNavigatedTo with no parameter, and then back to the SecondPage OnHardwareButtonsBackPressed and then back to FirstPage OnNavigatedTo with filled parameter.

Could you please advice me some better approach?

Upvotes: 0

Views: 1381

Answers (1)

Peter Torr
Peter Torr

Reputation: 12019

In your back handler, don't navigate forwards again, just call GoBack -- and it's typically easier if you handle that at a global level rather than at a page level.

You can store your application state (the things you want to persist across page navigations) in global / static objects, or you could directly modify the object that was passed from the initial navigation (if the calling page still has a reference, it will be able to see the changes).

I would consider doing a search for "MVVM Windows Apps" and looking at some of the results to learn about a common way of building XAML apps.

Upvotes: 3

Related Questions