Using Blend Sample data at Design time and real data at Runtime
Sample Data is Awesome
Here’s a clever trick that I found out the other day – one of Blend 3′s best features is Sample Data, which allows you to generate basic data structures in Blend, create sample arrays of them, and mock up UIs so that your DataTemplates actually show something useful. This is a huge improvement over Blend 2 and VS, where important parts of your UI would basically be invisible until you actually could build the project and populate it with real data.
Keep Sample Data all the time
One thing I always struggled with though is, that you always had to switch the binding back and forth between the sample data and the real data – even though Blend has a “Only enable sample data at design time” feature, you could still only bind the data to one place. But there’s a clever hack to get around this, you can see me applying it in this Github commit.
Basically, say you had a Listbox:
<!– Sample Version
<ListBox ItemsSource="{Binding Path=Data, Source={StaticResource SampleData}}" />
–>
<listbox ItemsSource="{Binding Path=TheData}" />
</grid>
Here’s the trick – Blend doesn’t let you redirect the binding at Design time, but it will let you redirect the context. So all you have to do, is group the ItemsControl in a meaningless container, then rig the DataContext; d:DataContext is what Blend will use at Design time and will be ignored by WPF / Silverlight.
<border DataContext="{Binding Path=TheData}" d:DataContext="{Binding Path=Data, Source={StaticResource SampleData}">
<listbox ItemsSource="{Binding}" />
</border>
</grid>
Et, Voila!
Now, whenever we edit in Blend we see our sample data so we can edit the UI, then when we run it, we’ll use the live data instead.
