What are your strategies of binding the DataContext in MVVM? What are your strategies of binding the DataContext in MVVM? wpf wpf

What are your strategies of binding the DataContext in MVVM?


Did they mention why the different approach was used for Silverlight? It may just be a limitation of the platform.

The recommended approach is to absolutely use the view model itself as your view's DataContext. In fact, rather than creating the view explicitly, you should be creating the view model and have WPF resolve the view for you. To do so, register a DataTemplate:

<DataTemplate DataType="{x:Type local:MyViewModel}">    <local:MyView/></DataTemplate>

Then you just stick your view model instance into a ContentControl, ItemsControl or whatever and WPF will render it with the appropriate DataTemplate. That DataTemplate will have the view model as its DataContext, by virtue of WPF's templating system.


If you read the comments for the Silverlight video you'll see that the binding to an ObservableCollection was a mistake. It causes an exception to be thrown.

Most of the time the View is bound to the ViewModel (I can't in fact think of a reason when I wouldn't do that)

Kents example above is the general rule I follow, getting Silverlight to create the view for me given a collection of ViewModels.


I've had some support from some exceptionally gifted MS engineers on our project and they are binding the View datacontext directly to the the View Model.

Ideally, you should not have any code behind code other than your your data context setting - infact this can be done in XAML too.