The MVVM Light framework for Xamarin.Android provides a
NavigationService allowing for navigation to views to be invoked from code in a View Model command handler for example.
NavigationService has the limitation that an
Activity class must derive from an
ActivityBase class provided by MVVM Light. This itself derives from
Activity so the type of views which can be used are limited.
I recently ran into this problem whereby I needed to use a view with a
TabLayout which requires the
Activity to derive from
FragmentActivity. The purpose of this post is to provide an example which is based upon the MVVM Light
NavigationServicebut will work with any
Activity type and doesn’t require deriving from
The source code can be found on GitHub.
The code presented is the
NavigationService with very minimal changes – The class works great apart from the
I found a great post by Jim Bennett MVVMLight navigation and AppCompatActivity which presents a solution to the problem in the context of using
AppCompatActivity. If you are in this scenario take a read because Jim provides code on GitHub and a Nuget package so this would be your quickest solution.
At first I tried to just use the
Activity deriving from
FragmentActivity with the
NavigationService and it worked to navigate to the view, but blew up with an exception when navigating back so be aware of this.
I have used the Plugin.CurrentActivty Nuget package written by James Montemagno. See his post Access the Current Android Activty from Anywhere! for details of how to use this elsewhere in your Xamarin.Android app. James also provides a Nuget package Plugin.currentActivty.
In additon the
DispatcherHelper classes depend upon
ActivityBase so I have provided examples using the Plugin.CurrentActivty rather than the
The example app provides a Home View and a Child View. There are buttons on each page to navigate to the other page. The Home View has an
EditText into which an integer parameter can be entered. This simulates passing an Id as a navigation parameter to the Child View, the value is displayed on the Child View.
The Child View has a second button titled Show Message which demonstrates the
AlternateDialogService to show a Message Box.
The images below show the example app:-
The Home View