Navigation in the MVVM architectural pattern seems a pretty tough task and most commonly found solutions don’t really satisfy me.
They are overly complex, involve lots of code or don’t seem elegant at all. Some solutions just statically specify the target page as a
string (in Windows/Windows Phone/UWP apps):
In Xamarin.Forms, navigation requires you to specify an instance of
Page to navigate to. Usually, you would write code like this:
This is bad for a couple of reasons:
Navigationis a property of the
Pagetype – you’ll have to somehow pass this to your ViewModel or have some kind of glue in your code behind.
- Since we’re calling the constructor of
SubPagehere, we’re coupling these classes tightly. This means we cannot comfortable test the navigation portion in our ViewModel.
- Navigation without Pages is not possible – that means that unit tests would rely on the Xamarin.Forms framework, which they should not need to.
In this article, I will present a pattern that – at least in my eyes – solves these problems while still allowing easy configurability and short, elegant code. Let’s get started.