Differences between the navigation and ViewModel approaches

In this section, we will take a look at the approaches when performing navigation within ViewModels contained within an Xamarin.Forms solution. When performing navigation within your ViewModels, there are a couple of approaches that you should consider before going down this path. An approach would be to use the page navigation approach, which involves navigating to another page using a direct reference to that page.

The page navigation approach can be accomplished in Xamarin.Forms by essentially passing the current INavigation instance into a ViewModel's object constructor, which will force the ViewModel to use the Xamarin.Forms default navigation mechanism to navigate to other pages.

If you wanted to use the ViewModel approach to navigate to a page using the associated pages ViewModel, you would need to form some sort of mapping between each of the pages, as well as their associated ViewModels. This would be done by creating a dictionary or key-value type property in the navigation service that will maintain a one-to-one mapping for each of the pages and their type.

In MVVM, actions taken by the user on a particular page are bound to commands that are part of the pages, ViewModel, and so this process needs to be thought through differently when navigating to another page, or even the previous page, when performing tasks such as saving data or updating a maps location. As such, we need to rethink how to achieve navigation that leverages the MVVM design pattern within our app, so that it can be controlled by the ViewModels and not by the underlying pages.

When using the ViewModels to handle the navigation, this alleviates the need for a ViewModel to have any dependencies on the specific implementation of a page, and because the ViewModel doesn't navigate directly to a page via the ContentPage's ViewModel, this means that when you implement this approach, there is a need for a relationship or mapping to be done between each of the pages and their associated ViewModels.

In the next section, we will be taking a look at how to navigate through our TrackMyWalks app by creating a navigation service that will include ViewModel and page type mappings.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.14.144.108