What is the advantage of setting DataContext in code instead of XAML?
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
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.
Having it in codebehind makes it easy to inject the datacontext using unity.