When developing an application it is often time consuming having to deploy the application to a device or the emulator to see how a specific view or template might look like with real data. This is where sample data comes in handy. Using the design-time tools available to us in Visual Studio and XAML we can inject sample data to our views.
Creating the sample data
In this example application we’re using the MVVM-pattern for structuring our code, and we have a viewmodel named MainPageViewModel that we want to mock up. The MainPageViewModel contains a collection of MenuItems that is populated at run-time. The view (PhoneApplicationPage in this example) contains a ListBox that binds to that collection. To see what a MenuItem will look like when running an app, we can bind the view to a sample instance of the MainPageViewModel. Fortunately, all of this can be done using XAML.
The first step is to create a new XAML file. In this example it’s called MainPageViewModelSampleData.xaml and is placed under a fictious folder named SampleData:
<models:MainPageMenuItem Title="Search" />
<models:MainPageMenuItem Title="Maps" />
<models:MainPageMenuItem Title="Something cool" />
<models:MainPageMenuItem Title="Settings" />
The code above shows the contents of the sample data for our MainPageViewModel. The XAML is pretty self-explanatory: we first create a new instance of MainPageViewModel and can manipulate all of its properties using XAML. The MenuItem collection is easily populated with MainPageMenuItems, which contains a Title property we’re setting.
Using the sample data
To use our XAML sample data we can tell our view to use it as a source for DataContext during design-time:
After setting the DataContext property you will (hopefully) immediately see the ListBox containing our sample items. This is extremely useful when crafting views and item templates.
If you have any questions regarding using sample data, please feel free to comment below and I will try to answer as best I can.
Thank you for reading.