James Montemagno
James Montemagno

Live, Love, Bike, and Code.



Xamarin.Forms XAML Previewer Design Time Data

James MontemagnoJames Montemagno

The most annticipated announcement of Xamarin Evolve 2016 had to be the Xamarin.Forms xAML Previewer. Enabling you to see a live preview of your Xamarin.Forms XAML without having to run it on a simulator or device. Simply write some XAML and there it is running on an iOS or Android phone or simulator design surface.

Writing XAML and seeing it is fine, but what if you want to see sample data right inside of your preview? I mean doesn’t each View have a ViewModel associated with it? If so, then would’t we like to use it during design time?

Return of the ViewModelLocator!

During the keynote Nina showed off a list of Coffees where the ItemSource was bound to some design time data. I first thought about taking this approach and create a static List for my Monkeys app, but then I thought there has to be a better way. Essentially, Laurent taught us years ago how to create a static ViewModelLocator class that can be used at design time. So here is the setup, simply create a new class called ViewModellLocator.cs and create a static version of each ViewModel you wish to use (I personally put it in my App.cs):

public static class ViewModelLocator
    static MonkeysViewModel monkeysVM;

    public static MonkeysViewModel MonkeysViewModel => 
       monkeysVM ?? (monkeysVM = new MonkeysViewModel());

Note: you could pass in some additional arguments to tell your view model you are in design mode.

Design Time

Next up is to head over to your XAML file and create a new xmlns:design on your Page that refers to the assembly that you are using.


Then you can set BindingContext of the page to your design time static view model:

BindingContext="{x:Static design:ViewModelLocator.MonkeysViewModel}"

See it live!

Now the rest of your Bindings will all just work, which is pretty much fantastic.

Here is a short video walking through the process:

Don’t forget that it even renders your custom renders. Awesome! Be sure to read the Evolve blog post announcing all these awesome features.

Live, Love, Bike, and Code