This Xamarin how-to article shows (in my opinion) the easiest and cleanest way to implement the MVVM pattern in a DataTemplate.  The example I will be using is a ‘set up wizard’ using a standard Xamarin.Forms CarouselView and IndicatorView.  The example show how you can keep each ‘page’ in the setup wizard separate with a separate view model also even though they are all contained within the same navigation page.

The Main XAML Page

This is the simple XAML page code that will hold all of our individual pages/templates within a CaraouselView with indicator dots on the bottom of the page. It can be seen that we still need to create a ViewModel and a TemplateSelector which will be covered.

Templates & Template Models

Next we can create all of our DataTemplates that we want to use in our wizard, along with a ViewModel for each. The ViewModels will all be inheriting from a base ViewModel. The main thing that we need to remember is that when using bindings from our ViewModel in our DataTemplate, we need to prefix the property name with “Model.”.

The Wizard Model

Now that you have seen an example of what a template looks like and the corresponding TemplateModel, you can now create the rest for the remainder wizard steps. We need to now create a Wizard model to create a list to use on the Main ViewModel. This will automatically retrieve the TemplateModel based on the enum.

The Wizard Template Selector

Now that our Wizard model automatically retrieves the TemplateModel we will use a DataTemplateSelector to retrieve the correct page. By inheriting from the DataTemplateSelector from Xamarin.Forms we can automatically retrieve the Page/DataTemplate based on the enum as shown below.

The Main ViewModel

Now that we have everything in place, we can finally create a List with all of our wizard pages and corresponding models.

That’s all for this time, you now have an easy and expandable pattern to use for DataTemplates so that we are able to keep everything clean and MVVM.
Full source code available here.