There seem to be two main ways to define DataContext in WPF:
App.xaml.cs (taken from the WPF MVVM Too
In my experience, it is best to design an interface layout against at least a sample of the data it will present. To do otherwise is to be blind to cheap insights and expensive oversights.
Having it in codebehind makes it easy to inject the datacontext using unity.
There could be a kind of solution to this, using the DataObjectProvider to mask the fact that the data is instantiated outside of XAML.
It will state what the type of the DataContext is, which should be enough for Blend to pick up the properties.
I have not tried this yet, so take it with a grain of salt, but it is certainly worth investigating.
You can (maybe in 2009 you couldn't) get the best of both worlds by using the d:DataContext
attribute. You don't need any of that ViewModelLocator craziness if you're not ready for that yet :-)
First make sure that you have the following XML namespace defined in your root element:
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
Then you can add the following attribute to an element in your xaml:
d:DataContext="{d:DesignInstance IsDesignTimeCreatable=True, Type=vm:CustomerInsightViewModel}"
In your xaml codebehind :
public CustomerInsightUserControl()
{
InitializeComponent();
if (!DesignerProperties.IsInDesignTool)
{
DataContext = new CustomerInsightViewModel();
}
}
Then in your ViewModel:
public CustomerInsightViewModel()
{
if (IsInDesignMode)
{
// Create design time data
Customer = new Customer() {
FirstName=...
}
}
else {
// Create datacontext and load customers
}
}
Don't miss the IsDesignTimeCreatable=True
or else Blend won't instantiate your class
See Rob's article about design time data in Blend: http://www.robfe.com/2009/08/design-time-data-in-expression-blend-3/
I don't like the idea of having Expression Blend try to instantiate my data objects.
I set the DataContext through code where I am able to use Dependency Injection to inject the proper objects, services, providers or what else I am using to find my code.