OK, let’s say I am creating a program that will list users contacts in a ListBox on the left side of the screen. When a user clicks on the contact, a bunch of messages or whatever appears in the main part of the window.
Now my question is: how should the MVVM triads look? I have two models: Contact, and Message. The Contact model contains a list of Message models.
Each ViewModel object will contain a single corresponding Model, right?
And what about the Views? I have a “MainView” that is the main window, that will have things like the menu, toolbar etc. Do I put the ListBox in the MainView? My confusion is with what to put where; for example, what should the ContactView contain? Just a single instance of a contact? So the DataTemplate, ControlTemplate, context menus, styles etc for that single contact, and then just have a ListBox of them in the MainView…?
Thanks.
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.
Now you can bind these properties to your MainView like this
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?
How are these wired up?
That’s it. This is how I’ve understood MVVM.
And about the point,
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.