MvvmCross changing custom view without following a convention

Oct. 3, 2013 jmgomez | Mobile , MvvmCross
MvvmCross changing custom view without following a convention

 

 

In MvvmCross when you create a view for a ViewModel you usually just have to follow the convention. For example, for a ViewModel called MapViewModel the name should be MapView. But what happens when you want to show a different view for that MapViewModel? I'm working on a project which has online and offline maps, for the online implementation I chose Google Maps and for the offline I chose OpenStreet with the RouteMe implementation (I did a pull request supporting offline map in Xamarin.iOS, you can find the repo in the official MonoTouch library bindings).

So, the scenario is the following: A MapViewModel which contains almost all the presentation logic, an abstract class which inherits from MvxTouchViewController and contains the behaviour of the screen, and finally RMapView and GMapView for RouteMe map and GMap. I'm showing it in a TabBarController, if you saw the N+1 videos, @Slodge showed this method:

 

public UIViewController CreateTabFor(string title, string imageName, IMvxViewModel viewModel){

var controller = new UINavigationController();

var screen = this.CreateViewControllerFor(viewModel) as UIViewController;

SetTitleAndTabBarItem(screen, title, imageName);

controller.PushViewController(screen, false);

return screen;

 

I modify it just to show my maps (in the other tabs I keep using it), and it looks like this:

 

public  UIViewController CreateTabForMap (string title, string imageName, IMvxViewModel viewModel) {

var controller = new UINavigationController();

var screen = RouteVM.MapViewModel.IsOfflineMap ? (MvxViewController)new RMapView()

   : (MvxViewController) new GMapView();

screen.Request = new MvxViewModelInstanceRequest(viewModel);

base.SetTitleAndTabBarItem(screen, title, imageName);

controller.PushViewController(screen, false);

return screen;

}

 

The key is to replace the CreateViewControllerFor extension method. Internally it instanciates the View and creates the request, which is what I'm doing here. 

As you can see MvvmCross is a very extensible framework for cross platform developtment. Try it out!