Anonymous
Anonymous

Reputation: 9648

Confusion with WPF MVVM

I have downloaded the document about MVVM from CodePlex, but I don't understand this diagram.

alt text http://img194.imageshack.us/img194/3959/diagram.png

In the document, ContactView never sets its DataContext to ContactViewModel, so I don't understand why this diagram has shown that ContactView refers to ContactViewModel via DataContext.

I don't know when it sets ContactView.DataContext, or is the document missing this point?

Upvotes: 0

Views: 501

Answers (1)

Martin Harris
Martin Harris

Reputation: 28617

It may not need to specifically set the DataContext if the contacts are being shown in a listview or something similar.

If the datacontext of the listview is set to the Contacts property of the MainViewModel, then each item's datacontext will be set automatically to the specific ContactViewModel object, which may trigger the items to be presented using a ContactView control, assuming that certain template bindings were set up earlier in the document.


Sorry, I was having problems with codeplex and have only just managed to get the document to download. The block of code just before the diagram confirms my suspicion:

<Grid>
    <ListBox ItemsSource="{Binding Contacts}">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <views:ContactView />
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>
</Grid>

Since the ListBox is bound the the Contacts ObservableCollection each ListItem will have its DataContext set to the specific object that it is bound to. The DataTemplate is set up to show each item as a ContactView control. Therefore the ContactView's DataContext will be set to the right Contact object from the collection, all of this happens behind the scenes without you needing to actually set the property yourself.

Upvotes: 1

Related Questions