Xamarin.forms shell brings a lot of changes to the navigation, unlike standard navigation it does not use a stack hierarchy. In many ways shell navigation solves many issues that we may come across while using MVVM.
But, it also has its fair share of shortcomings, for example while passing data during navigation the gotoasync method only accepts string and not an object.
Beginners may find it a bit annoying that there is no such method inbuilt to pass an object, but that’s not a big problem.
This post will demonstrate step by step on how we can pass an object type as data in gotoasync method.
We first need to serialize our object using Json serialization into a string,
Pass this string into the gotoasync method and,
Deserialize the string that we receive on the other page.
To better explain it we will take a sample project as an example:
Our motive is to enter details on Page1 and navigate to Page2 using gotoAsync method,
The details is a class called data with properties like Name, Email, city and State.
We want to pass an instance of this class to the gotoasync , receive it on the second page and display the labels.
Note that we are using data bindings but not MVVM, which will be quiet identical to what we are doing here.
We start with our page1 code behind where we set all the properties that the object will contain.
Our page1 UI will have a button which when clicked will instantiate a new Data class by assigning the value to the properties.
Serailize it in the form of a string and pass it into the gotoasyn method.
The highlighted text demonstrates how to serialize the object and how to pass it.
We need to make sure that we have added the using Newtonsoft.Json package and set the relative route to page 1.
2) Receive and process the serialized object on the second page
We basically repeat the previous steps, that is, we specify all the properties that will contain the values when the string is deserialized,
Most important thing to note is to specify the query attribute that we passed earlier in the gotoasync method on page 2.
3) Now we deserialize the string
This method allows us to bypass the limitation of not passing of an object,
Instead we pass a serialized string and deserialize it later on.