Passing Data on Navigation in Xamarin Forms

A common issue in many Xamarin Forms applications, is how to pass information from one page to another, during navigation. They are a few options, and how applicable they are, depend upon your app setup, and your specific use case.

Constructor Arguments

If you are manually handling all the navigation yourself, you will be using the default Xamarin Forms navigation. When you do this, you need to create a new instance of the page. Some MVVM frameworks are also built around this principle.

await navigationPage.PushAsync(new MyNewPage());

The simple way of transferring data here, is just to pass an argument in the constructor.

await navigationPage.PushAsync(new MyNewPage("my argument"));

It’s really simple, but not very efficient, as you then have to pass data back to your ViewModel, within the page.

MVVM Arguments

If you are using an MVVM Framework, they can make things far easier for you. A few examples below, show an MVVM framework passing a parameter through the navigation service.

// Exrin
_navigationService.Navigate("Key", argument);

// Then in your ViewModel, it comes in on the OnNavigated event
protected override Task OnNavigated(object argument) {}
// Prism
_navigationService.NavigateAsync("MainPage", navigationParams);

MVVM frameworks, may also expand on this, such as Exrin, and provide argument pass back on PopAsync.

Model State

The next way to do this, is to store data in your Model. e.g. In your Model, you have a Login function. When you call the Login function, your store the value, in your Model.

private string _email;

public void Login(string email, string password)
{
   // ..... Do login and if success

   _email = email;
}

Now when you go to the next page and need to see the email address used for login, just collect it from the private property. This works, when your ViewModels are all referencing the same Model.

Not MessagingCenter

I just wanted to mention, not to use this method. I go into length on various reasons why in Misuses of MessagingCenter. It should only be used in rare circumstances. Please note, this is my opinion, and others take a different view.

Microsoft MVP | Xamarin MVP | Xamarin Certified Developer |
Exrin MVVM Framework | Xamarin Forms Developer | Melbourne, Australia

Related Posts

Leave A Comment?