Most navigation service helpers or code I have come across just construct a new instance of a page and pass it to the stack, normally within the navigation service. I prefer to implement a factory pattern to build the page as it lets you control the page to finer degree and you can swap out page building factories within your code if necessary.
In my Page Building Service I do 3 things
- Map a page type to a view model type
- Construct the Page
- Locate the ViewModel and set to the pages BindingContext
An example of my PageService.cs
ViewModel to Page Mapping
Normally a ViewModel is set to the BindingContext within the page code behind.
But the traditional approach has 2 major cons.
- Your page has code behind to set the binding context.
- Your ViewModels as static references publically accessible around the application.
A new approach as shown in the page service allows
- BindingContext is set when the page is constructed in a central location
- No code behind is needed on the View, keeping it squeaky clean
- Mappings between Page and ViewModel are defined in one location and not scattered around.
When I create my Navigation Stack (coming up later) – you will see the MapViewModel method. This is where I map a page type to a view model. The great thing about this is you can even reuse Views and ViewModels if needed as neither of them ever have a reference on each other.
Extending on managing the page construction, we can manage the page destrucstion as well. At point we need to create a new NavigationPage. An example is ExtNavigationPage.cs
In this, I manage the OnPopped event, and in each page, we reference a cleanup event. The cleanup event is just a virtual method in a common base page inherited by all the views. While Xamarin Forms is meant to clean up everything, I find at times it fails to wipe everything, hence why I explicity set it.
While each page can do any further cleanup, here I make sure that the BindingContext, Toolbars and Content are all set to null.