The problem is this: You’ve created your Views and ViewModels, but when you view them in Blend, you either see nothing, or the data you see is not useful for testing what you want in the view. There are various ways to deal with this, including writing code (either in the ViewModel or in a service locator) to return different data at design time.
I’m going to demonstrate a different way that doesn’t involve code, and is very simple and most importantly: Malleable.
Assumptions/Prep:
What we’ll do:
Go to the “Data” tab, and create sample data from a class:
Select your ViewModel as the class to base the sample data on. This is a giant time-saver:
A new folder + file will be created: SampleData\BooksSampleData.xaml. It’s pre-filled with fake data and ugly namespaces. For readability, I’ve done a find/replace on the namespaces. Here’s what I get:
<m:BooksViewModel xmlns:m="clr-namespace:MVVM_DesignTime_Test.ViewModels" IsSearching="True" SearchError="Vestibulum cras" SearchString="Lectus fringilla eros"> <m:BooksViewModel.SearchResults> <m:Book Author="Aliquam aenean" Name="Curabitur maecenas class" Price="216.9"/> ...... <m:Book Author="Nec non" Name="Dictum etiam" Price="920.1"/> <m:Book Author="Elit fermentum enim" Name="Erat fusce" Price="597.75"/> </m:BooksViewModel.SearchResults> </m:BooksViewModel>
Two interesting things to notice about the above:
This is where the magic happens. Look back at the Data tab, and see that this new sample data source is now listed:
Simply drag-drop this guy onto the control which should use it as the data context. The mouse cursor will display text explaining what it will do. In my case, I dragged it onto the LayoutRoot grid, since I wanted everything under that to use it. Once this is done, you’ll notice a new XAML attribute on that control:
d:DataContext="{d:DesignData /SampleData/BooksSampleData.xaml}"
This is the magic, especially the “d:” namespace declaration, which you’ll notice is mentioned in the page’s XAML declaration as such:
mc:Ignorable="d"
Now when you select the “Data Binding…” context-menu for a control’s property, it will show you the properties that come from this data context, which correspond to your ViewModel, with the correct names, types, etc:
And BAM – there’s the data: