View Model Navigation by Convention in MVVM Light

Having not used MVVM Light for a while, I came back to it recently to put together a small Xamarin.Android app. It’s a great toolkit and I’d forgotten just how quickly you can get up-and-running with navigation, bindings and tests.

When it comes to hooking up the NavigationService, i’ve started to adopt a view model navigation pattern that differs from the usual MVVM Light navigation examples.

MVVM Light navigates by page keys. These are string constants that you define yourself and register for each page that you will need to navigate to in your application:


public const string HomePageKey = "Home";

protected override void OnCreate(Bundle bundle)
{
   ....

   var nav = new NavigationService();
   nav.Configure(HomePageKey, typeof(HomePageActivity));
   
   ....
}

To navigate to a particular view through your cross-platform code, you simply get hold of the navigation service and use the required key without any knowledge of which platform page implementation you are invoking:


nav.NavigateTo(HomePageKey);

While this works well, i’m more at home with view model navigation after spending a lot of time with MVVMCross and immediately started thinking in those terms. I soon realised that if you just adopt a convention of navigating to the view model name, and use the C#6 nameof keyword, you don’t need key constants at all:


protected override void OnCreate(Bundle bundle)
{
   ....

   var nav = new NavigationService();
   nav.Configure(nameof(HomeViewModel), typeof(HomePageActivity));
   
   ....
}

It’s a simple convention that you can agree to adopt with anyone else working on your codebase, that becomes the standard way to navigate to a view:


nav.NavigateTo(nameof(HomeViewModel));

So if view model navigation is something that might work for you, consider deleting those keys!

Advertisements

2 thoughts on “View Model Navigation by Convention in MVVM Light

  1. I do that too 🙂 sometimes the navigation is a bit more complex because you can have multiple views per VM (think about the case where you have a tablet page that you split in two pages on a phone, for instance) but for sure nameof is a good help even in such cases.

    Liked by 1 person

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s