The heart of MVVM pattern is the Model which is the structure of your data. So you have the Contact Model and the Message Model which are related and is well set. Now you want to design your interface. The UI contains a single window(the MainView). So you would need a single ViewModel. So what does the ViewModel consist of?
Let us assume that you want to display only a single contact in your MainView and not a collection. Now your MainViewModel can just have references to your Contact's properties which are to be exposed into the view.
Contact c = /*Retrieve a contact from db*/;
ContactName = c.Name; //Create these two properties
ContactPhone = c.Phone; //Assuming only these two properties are required by your view
Now you can bind these properties to your MainView like this
<Textbox Text={Binding ContactName} /> <!-- Assuming the DataContext is assigned -->
<Textbox Text={Binding ContactPhone} />
But we have to display a collection in our MainView. Hence we define the individual listitem as a new view. We also need a list of ContactName and ContactPhone. Hence we wrap these two properties into a class and make a list of it. This Class is termed as ViewModel.
(Here you have to add Messages Property also)
Hence the individual views have their own viewmodel. Now we integrate these views into our MainView.
Now what should the MainViewModel contain?
- List of ContactViewModels - ContactList
- Selected ContactViewModel - SelectedContact
- List of MessageViewModels - SelectedContactMessageList
How are these wired up?
- ContactList - bound to Contact ListView
- SelectedContactMessageList - bound to Message ListView
- SelectedContact - bound to Contact ListView's SelectedItem. The setter should modify the SelectedContactMessageList according to the Selection like this
SelectedContactMessageList.Clear();
foreach (Message message in SelectedContact.Messages)
{
SelectedContactMessageList.Add(new MessageViewModel(message))
}// converting the resulting models from SelectedContact.Messages to viewmodels
That's it. This is how I've understood MVVM.
And about the point,
Each ViewModel object will contain a single corresponding Model, right?
No! Instead each View is mapped to a single ViewModel
Create a ViewModel for each View in your application and have only those properties that are required by your View, in your ViewModel.