Skip to content

Tag: Models

Xamarin.Forms, MVVM, and Navigation

Coming from a Xamarin native background, I was not entirely familiar with the MVVM pattern prior to switching to Xamarin.Forms. The native designs for iOS and Android typically follow the MVC pattern. MVVM was designed by Microsoft specifically for applications that utilize XAML to design their UIs. If you are familiar with MVC, MVVM is not wildly different. MVVM stands for Model-View-ViewModel.

MVVM Pattern
Source: Microsoft.com

A very rudimentary way to describe MVVM is that you have your typical data models which make up the Model part of the acronym. These data models represent the objects and business logic within your application. Next, we have the View; this is exactly what it sounds like, essentially everything that is rendered on the screen is part of the View.  The ViewModel is the unique (or not so unique) aspect of the pattern. This is where all of your view logic and states are handled. Additionally, the ViewModels act as the middleman between the Views and the Models.

The main objective to using the MVVM pattern is to create loosely coupled code between the Views and the ViewModels. In other words, the Views know about the ViewModels; however, the ViewModels should not know about the Views. Additionally, the Views should not know about the (data) Models and the Models should not know about the Views, or the ViewModels. The purpose behind such a design allows developers to quickly and easily swap out Views with other Views without having to change the business and application logical. Furthermore, this design allows separate teams to work on different components of the project. For example, on a large team, designers could work on the Views of the application (in XAML without any other programming knowledge), while developers could handle the ViewModels, and Models.

Xamarin.Forms was designed with MVVM in mind due to the adoption of XAML. Most of the framework has implemented the tools necessary to utilize the MVVM pattern. However, in my opinion (and the opinion of others) one aspect of the framework design completely breaks the MVVM pattern, and that is navigation.

Xamarin.Forms handles navigation using the INavigation interface available on any Page type (aka the Views). INavigation acts as a globally available navigation stack for your entire application. You might be thinking, that’s great, what’s the problem? The main problem, is that the Views are in charge of handling navigation, not the ViewModels. This technically breaks the MVVM pattern because the Views are dictating how your application operates, not the ViewModels. Under this design, it becomes very difficult to replace a particular View without fixing the logical structure of your application.

So what’s the solution? The solution is to move all of your navigation logic into your ViewModels. In my next post, I will go into detail of how to do this using a framework called MVVM Light.