What are your DataContext binding strategies in MVVM?

These two one-hour videos show step-by-step how to use the MVVM template to create simple quiz applications in both Silverlight and WPF:

Implement Model-View-ViewModel in Silverlight

Implement Model-View-ViewModel in WPF

What strikes me is how different they are from structural ones , for example, how they use a DataBinding:

In the Silverlight approach, we set the DataContext of the view to an ObservableCollection in the ViewModel :

<views:QuestionView x:Name="QuestionDataView" /> QuestionViewModel qdata = new QuestionViewModel(); qdata.FetchQuestions(); QuestionDataView.DataContext = qdata.Questions; 

In the WPF approach, we set the DataContext of the window to the ViewModel itself .

 <view:QuizView Margin="4" /> base.DataContext = new QuizViewModel(Quiz.Create()); 

It seems that every MVVM example that I am looking at is binding a DataContext to a slightly new variation, and I'm trying to mute the solid ground relatively, " like a DataContext binding in an MVVM pattern .

What happens when you decide to bind a DataContext to something: why bind a DataContext Window / View / ListBox / etc. with ObservableCollection / ModelView / etc. ? What are the advantages, disadvantages, strategies here?

Any input is appreciated.

+6
design wpf silverlight mvvm conceptual
source share
3 answers

Did they tell why a different approach was used for Silverlight? It could just be a platform limitation.

The recommended approach is to absolutely use the view model as your kind of DataContext . In fact, instead of explicitly creating the view, you should create a view model and WPF allow the view for you. To do this, register the DataTemplate :

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

Then you simply insert the instance of the view model into the ContentControl , ItemsControl or whatever, and WPF will display it with the corresponding DataTemplate . That the DataTemplate will have a presentation model as its DataContext , by virtue of the WPF template system.

+10
source share

If you read the comments on the Silverlight video, you will see that binding to the ObservableCollection was a mistake. This throws an exception.

In most cases, the view is related to the ViewModel (I can't really think of the reason I didn't)

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

+3
source share

I had the support of some exceptionally talented MS engineers in our project, and they bind the View datacontext directly to the View Model.

Ideally, you should not have code after code other than setting your data context - infact can do this in XAML.

+1
source share

All Articles