MVVM WPF ViewModels for Adding New Entity - wpf

My concept for MVVM in WPF is that we have a ViewModel for every Model in your application. This means that if we have Customer class (entity) then we will have CustomerViewModel. The CustomerViewModel will have all the properties which are necessary to represent a customer. The CustomerView usercontrol will be responsible for creating the UI for the Customer model.
Now, let's say that we are adding a new customer. So, we have a form which consists of FirstName, LastName etc. Do we need a ViewModel for this scenario. I mean all I have to do is to take all the input values from TextBox and create a Customer object and then save it to the database. Why should I bother creating a ViewModel for this scenario?

First of all, that is not the main purpose of MVVM, to "mirror" everything. The View should provide the means for a user input, and certainly not process calls to any of the database layers. The ViewModel should be a GUI-agnostic application backbone, and it definetly should handle the creating of customers.
That said, what you should do, is have a ViewModel which represents a workspace for handling customers, and not just a customer ViewModel. If you really want to save on a few objects being created, add to that workspace the possibility to create and add a new customer (not CustomerViewModel). That way, you can have a View of the workspace which has elements for each relevant/required property of the customer, and by invoking some command added to that workspace ViewModel, you could get the current values filled in those (data bound to ViewModel) View elements directly to the customer model.
Consider if you could probably drop the specific customer (and other Model) ViewModels if you refactor things a bit, it would be good practice to keep things from adhering blindly to a certain pattern without explicit cause.

Let's pretend for a second that there is no business model. The only thing you have is a view. If you were to model just that view, without any knowledge of what the data means elsewhere in the system, that is a ViewModel.
The goal of a ViewModel is to, well, model the view it backs. This is a different goal than modeling the idea of a customer in your business domain. To say you will have have one ViewModel per business entity, then, is to say you will have one view per business entity, which leads to run-of-the-mill data-focused UI.
In your particular case, think about the customer edit view. It has fields that correspond to a customer's properties, and thus seems like a natural fit for binding to a customer directly. However, where on the customer object is the "Submit" action modeled? Where is the "Cancel" action modeled? Where is it modeled that field X is an enumerated value selected from a list?
How about the password? If persisted as a binary hashed value, does the view know how to hash its text? What if the system has password strength requirements?
The ViewModel is the mortar between the business model and the UI. It takes concerns from one and translates them into terms of the other. It is the point at which all the above issues are addressed. To say a ViewModel isn't necessary is to ignore its necessity.

You don't need to have a separate ViewModel for Add, you only need a single ViewModel which should do Edit and Add scenarios. If you can delete the record from the edit page than that ViewModel should also have the ability to delete. Your ViewModel should reflect the functionality your View exposes regardless of data.
I think you should reconsider having a single ViewModel for each model. I like to think of ViewModels as normalizing behavior inserted of data. By having a ViewModel for each Model class you will run into architecture issues sooner or later. I look at the application from top down overview, what is my UI trying to accomplish and from there I will get to the ViewModel and eventually I will get to my DataFactory and how the ViewModel maps down to data is almost always not 1 to 1 except for the most simplistic Views. If you try to map 1 to 1 you will have bad UI or your data will not be normalized very well.
The Stack we have here is:
View
ViewModel (Controls everything the user can do in the view, wraps properties from our POCO's)
DataFactory (Maps our POCO's to Entity Framework objects and CRUD)
POCO's (Business Logic, all rules and validation)
Entity Framework (Model, Data Access)
One note here is that ViewModel contains properties from multiple POCO's!
We inject the DataFactory through StructureMap and Unit test with xUnit along with Moq.
To answer you second question I would create a separate view only view to drop in as a user control. But you should still have a CRUD ViewModel in you app that encapsulate all that functionality in a user friendly way.
Thanks.

One reason for this VM abstraction is for testability. Another reason why you want a ViewModel is because it's basically a Data Transfer Object that might be a combination of fields from multiple models in a single container that is more relevant to your current view. Yet another reason to have VM is to take advantage of WPF two ways binding capabilities.
Using your regular model (plain POCO), you can update the View when your model change, but since your model does not implement dependency properties (most likely), you won't be able to take advantage of updating your model when the value in WPF control changes. Which mean you have to manual add a handler and do the copy this value from this control back to the model kind of thing.

Related

Reusing WPF MVVM Views

I've inherited an application which uses the view-first MVVMC patern
In the application I've created 2 step process which creates a person and assigns them to a group. To do this I've created a view and corresponding view model (all views have a 1-2-1 relationship with a view model, view models are injected into the View constructor and are registered with the Unity container using the TransientLifetimeManager) called CreatePersonMaster, the view simply contains a region (shown by the dashed line) which sub-views can be loaded into and the view model subscribes to two loosely coupled events, "PersonCreated" and "GroupSelected". The "PersonCreated" event saves a Person entity in a field and the "GroupSelected" event takes the saved Person, creates a Group association and saves them to a database.
This view/view model doesn't do anything until the events get raised so I load the following sub views into my the region.
These views/view models fire the events which get handled by the master view.
I also have an edit view where I want to re-use the select group view.
I can do this by subscribing to the appropriate events in the EditPersonMaster view model.
My question really is, is this the appropriate way to do this? Because I'm using loosely coupled events I don't get any feedback into the sub-View/ViewModels if there's an error when creating/reassigning? I could probably fire another "ErrorBlah" event for the inner view/model to handle and update the view.
Is there another way to do this? Composite commands don't seem to fit the bill but maybe I don't understand them correctly.
Here is how I understood your question: You have persons stored in a database, which have a property/column group. In your UI, you want to create persons and assign the group property. Also, you want to be able to edit the group property of existing persons in a different region/page/master. You want to reuse the control for assigning the group. Your controls fire an event, which is handled by the Master in a way that it creates the entries in the database (is that correct?). Your question is whether this is a good approach and what alternatives you have?
I see two options:
1. Modularize your business logic:
You could inject a data service into your ViewModels, which could access the database directly. This way you can handle errors etc.. directly where they occur and don't have to pass them through the whole system. If you want to notify other modules of changes on the database (specifying the changed dataset or so), you can do so with a composite event. I think of the PRISM modules more as of complete elements, including UI and business logic and keep communication between them as little as possible.
2. Keep your business logic central and share it:
If you want to stick to your architecture, have singleton Model which is injected into the ViewModels. Manage your state in the model and have the ViewModels pick the pieces they want to provide to their view.
Hope I got he point, though...

What is the point of having both Model and ViewModel in M-V-VM?

I always find it tempting to put a model and a view-model together in one class, and I don't see the downside of doing that.
There must be a good reason for separating them. What am I missing?
ViewModel is the soft-copy of the View i.e. if you have a updateable ListBox on View, you will have an ObservableCollection in your ViewModel that represents that list of items in the listbox. Similarly if you have a Button on your View, the VM will hold its Command.
Model will be actually what has the data that the View shows. So the type collection in your VM is of, can be termed as a Model class.
E.g. a Employees ListView is a View, and has a data context which is the instance of EmployeeViewModel class that has an ObservableCollection property of Employee class where Employee class becomes a Model.
Usually there is 1-1 relationship between View and VM and 1-N relationship between VM and Model.
The model is the domain of your application and so contains your domain logic such as business rules and validations. The ViewModel is the model for your view. It handles the interactions between the user and the view, i.e. when the user clicks a button the view model will handle that interaction and may or may not make changes to the model. Normally in an OO language, you want your objects to have a single responsibility only.
In WPF the ViewModel usually implements the INotifyPropertyChange interface which is then observed by the view for any changes. You wouldn't want the model to implement this interface since it is not related to your domain in anyway.
Another reason for separation is that sometimes your view might not necessary show all data that is in the model. For example, if your model exposes 15 properties but in one of your view the user needs to see only 5 of those properties. If you place your model in the ViewModel the view would be exposed to all 15 properties whereas if you encapsulate the model in the ViewModel then only those 5 properties would be exposed to the View.
There are probably many more reasons but in general it is a good design principle to keep them separated. With that being said, if your application is small enough you can get get away with having your model and ViewModel together to reduce redundancy in your code.
The first real downside of doing this is a lack of separation of concerns. And soon this will lead to redundant code. Now, that said, I've seen a lot times where developers have used their Model objects as ViewModels. And if we're totally honest with ourselves, in a very thin app, separating these concepts can actually lead to more redundancy.
The best thing you can do is learn more about MVVM, and its roots in MVC and Presentation Model, but I think it's a great thing that you're asking this question and that you're not blindly following dogma. In fact, I often don't even start with MVVM at all when I begin a small app. I'll often start with a hundred lines or so in the code-behind, proving a concept, and then start refactoring it into MVVM.
More to the point of your question, the model and view-model have - in a conceptual sense - very different purposes. The Model includes your business logic (domain logic), data model (objects, attributes and relationships), and data access layer. The ViewModel is essentially an adaptor for the Model, adapting it for the specific purposes of the View. In some cases you might have 3 different views (and view-models) for a given data model object. Each view-model would be adapting those same attributes on the model object for the specific purposes of that particular view.
My simple answer (and I don't pretend to be WPF Guru) would be that , in WPF, you'd need a VM when:
1. You don't want to expose all your Model to a specific view
2. Your model is not in "WPF style" (doesn't implement INotifyPropertyChanged, no observable collections or no Commands).

How to create the ViewModel(s) for many Views sharing the same Model?

This is based on the example from the book:
Pro WPF and Silverlight MVVM by Gary McLean Hall
where the author only insists on how to create the Model for a DB structure (and how to implement the DAL for it).
I am looking for the correct way to create the ViewModel(s).
Here is the database model and the MVVM Model- I suspect it is not quite complete, but the Product is missing the ProductCode:
My Views will be: Pages displaying / editing views for Products, Customers and Orders
I am familiar with the Models / ViewModels implementing / using the INotifyPropertyChange and ObservableCollection, no need to insist on that.
My questions:
How to create the ViewModels in such a way that they would all share the same model
How do I manage the ViewModels? Do I have one Main ViewModel which aggregates all the specific ones? This relates to ViewModel state saving and restoring.
I am particularly interested in how to deal with this: the Model for Order has a List of Products. I will also have to maintain a list of Products for my ProductsViewModel which supports the displaying / editing Views for the Products. How can all be synchronized? Should the OrderModel only have a List of ProductCodes instead? What are the implications in that case?
In general, the thing I am after here is: how to create and manage the ViewModels for Models which implement DB tables with many to many relationships (like Product-Orders). Do we use only the foreign keys as part of the Model objects or do we use a reference to a whole other Model object represented by that foreign key?
To me it sounds like you are thinking about it the wrong way round. When you ask "How to create and manage the ViewModels for the Models which implement DB tables with many to many relationships" it sounds like you are thinking about ViewModels in terms of Models. Which isn't right. A ViewModel is a model of a View - not the Model. You shouldn't be thinking about creating ViewModels for your models, you should be thinking about creating VewModels of your Views.
In fact the model doesn't even come into it until the end. Start with your UI - your View. You then create a logical representation of that View in code so that you can bind to it, your ViewModel. Then finally you implement your ViewModel by accessing your Model to do what ever needs to be done. When you come to design the next View, even though it might contain some of the same data as the first, you would still create a new model for it - another ViewModel. Now the new ViewModel could include some of the same properties at the first ViewModel, which is fine. Remember is is a model of the View not the Model.
Consider an email app, with 2 views, summary and detail. Because there are 2 different Views you have 2 different ViewModels even though the are both pulling data from the same underlying model.
Model SummaryViewModel DetailsViewModel
----- --------------- ----------------
RecipientAddress RecipientAddress
SenderAddress SenderAddress SenderAddress
Subject Subject Subject
Content Content
Now the Summary View is only a summary and doesn't display the RecipientAddress or the Content so consequently those properties don't exist on the SummaryViewModel. The Details View displays more information, so has more properties. This same idea answers your question about foreign keys. Foreign keys are never visible on your View therefore have no business being members of your ViewModel. Your ViewModel cares only about what is required for the View.
In answer to your question "how do you manage the view models": you don't. You don't have to. ViewModel instances usually (not not always) have a one to one relationship with the Views, therefore you don't need to manage them. They only live as long as the view lives. You just create a new instance of the ViewModel when the View is loaded (typically in OnNavigatedTo event handler, see below) and store it in the View's DataContext. If two instances of the View are loaded, then there are two ViewModels. When the View is GC'ed, the ViewModel is too (if it isn't you have a memory leak).
Finally, as for how you should synchronize changes, that can be tricky in a desktop Silverlight app where many views might display concurrently. Fortunately on the Windows Phone we usually only have one view open at a time (although not always). So we can simply tell our ViewModel to refresh each time the page is navigated to:
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
base.OnNavigatedTo(e);
if (DataContext == null)
DataContent = new MyViewModel(); //Create new instance of the ViewModel
else
(MyViewModel)DataContext.Refresh(); //Refresh the existing ViewModel
}
This works well in most cases for more advanced scenarios you could look at the messaging infrasructure provided by a toolkit like Prism or MvvmLight.
Hope this has helped.

The model in MVVM: business object or something else?

I'm trying to get to grips with MVVM and so I've read a bunch of articles - most focus on the View -> ViewModel relationship and there's general agreement about what's what. The ViewModel -> Model relationship and what constitutes the Model gets less focus and there's disagreement. I'm confused and would like some help. For example, this article describes the Model as a business object whereas this article describes a class which manages business objects. Are either of these right or is it something else?
I think you are on the right track. The "model" is vague in a lot of cases because it is different things to other people, and rightly so.
For me, my business objects that come back from my WCF service I consider my model. Because of this my projects don't have that pretty file structure with the holy trinity of namespaces: *.Models, *.ViewModels, and *.Views. I personally consider objects coming back from business logic or anything of that nature the "model".
Some people tend to lump both the business objects and the business logic together and call that the "Model", but I find that a little confusing because I picture a Model to be sort of more static than I do business logic, but it's semantics.
So when you look at examples of MVVM projects and don't see anything very clearly "Model", it's just because folks treat them differently. Unless an application is very standalone, I would actually be very suspicious of an application with an actual *.Model namespace, to be honest.
The other thing that is great here is that many times you already have an investment in these types of business objects and I think a lot of people see "MVVM" and immediately assume they need to start defining the "M", even though what they already have is perfectly fine.
The confusion between a Model and a ViewModel is pretty common, too. Essentially I know I need a ViewModel if I need a combination of data and behavior. For example, I wouldn't expect INotifyPropertyChanged to be implemented on a Model, but I would a ViewModel.
From the other answers it should be obvious that the relationship between ViewModel and Model is somewhat fuzzy. Be aware that there is nothing stopping you from having ViewModel and Model in the same class, and when your requirements in a particular area are simple enough maybe this is all that you need!
How you structure the separation between ViewModel and Model will very much depend on the needs of the project or software that requires it, how demanding your deadlines are and how much you care about having a well structured and maintainable code base.
Separating ViewModel and Model is simply a way of structuring your code. There are many different ways of structuring your code, even within this pattern! It should be no surprise then that you will hear different approaches preached by different programmers. The main thing is that the separation can help to simplify and make reusable the independent portions of code. When you have cleanly separated business data, business logic and presentation logic you can easily mix, match and reuse your views, logic and data to create new UIs. The separated and simplified code is also often easier to understand, test, debug and maintain.
Obviously not everyone will agree with this answer. I think that is part of the inherent fuzziness of the problem. In general you need to consider and trade-off the advantages versus the costs of having a separation between ViewModel and Model and know that it is not always a simple task to decide what goes in the ViewModel and what goes in the Model. It will probably help to lay down some ground rules that you or your organisation will follow and then evolve your rules as you understand which level of separation best suits your problem domain.
I think it is worth mentioning that I used to use a similar approach to MVVM when programming Windows Forms and the fact the WPF has more direct support for this (in the form of data binding and commands) has really made my day.
There are a lot of different implementations and interpretations.
In my mind, however, the value of the ViewModel comes from coordination.
The Model is representative of business data. It encapsulates scalar information, as opposed to process.
The View is obviously the presentation of the model.
The ViewModel is a coordinator. In my opinion, the job of the view model is to coordinate between the view and the model. It should NOT contain business logic, but in fact interface with business services.
For example, if you have a view that is a list of widgets, and the widgets are grabbed from a service, then I'd posit:
The Model is a List<Widget>
The View is a ListBox bound to the ViewModel property Widgets
The ViewModel exposes the Widgets property. It also has a IWidgetService reference it can call to in order to get those Widgets.
In this case, the view is coordinating with a business object so the view doesn't have to know anything about it. The model should be ignorant of view models, views, and every thing else ... they should exist independent of how they are used. The IWidgetService would get bound to the view model using some source of dependency injection container, either constructor injection with Unity or an import using MEF, etc.
Hope that makes sense ... don't overload your viewmodel. Think of it as a coordinator that understands business objects and the model, but has no knowledge of the view or how business process is performed.
The value added by the model is its decoupling from the ViewModel and the View. Think if you had to construct and maintain business logic in the ViewModel you would have lots of duplicate code.
For instance - if you had a car game with a GearBoxView (a control in the CockpitView), CarViewModel and CarModel - the advantage of abstracting what is in the CarModel from the CarViewModel is that the CarModel can be used in the WorldViewModel and any other ViewModel. The CarModel can have relationships with other Models (GearsModel, WheelModel, etc).
Your question specifically asked about using a Model as a business object or to manage business objects: my answer is it can do both - and should be responsible for both.
Heres an example
public class WorldModel //Is a business object (aka game object)
{
private List<CarModel> _cars;
public List<CarModel> Cars
{
get //Here's some management of other business objects
{
//hits NetworkIO in a multiplayer game
if(_cars == null)
{
_cars = myExternalDataSource.GetCarsInMyGame();
}
return _cars;
}
}
public Level CurrentRaceCourse { get; set; }
public CourseTime TimeElapsed { get; set; }
}
I think of the model as something that contains the smallest units of business entities. The entities in the model are used not only across the view models in my application but even across applications. So one model provides for many applications and, for those applications using MVVM, many view models.
The view model is an arbitrary collection of entities from the model that are brought together to serve whatever the view needs. If a view requires 2 of these and 1 of those, then its view model provisions them from the model. Generally, I have 1 view model per view.
So a model is like a grocery store. A view model is like a shopping cart. And a view is like a household.
Each household has unique requirements. And each household has its own shopping cart that cherry picks what the household needs from the grocery store.
My thoughts
(The "Model")
Have one model. Just data no methods (except if apt for the platform some -simple- getters/setters).
(The "View Model")
To my mind the rationale for a view model is:
(1) to provide a lower-RAM-requirement backup copy of fields so views hidden behind other views can be unloaded and reloaded (to conserve RAM until they reappear from behind views covering them). Obviously this is a general concept that may not be useful or worthwhile to your app.
(2) in apps with more complex data models, it is less work to lay out all application fields in a view model than to create one reduced model corresponding to the fields of each possible data change, and easier to maintain, and often not significantly slower performance wise.
If neither of these apply, use of a view model is inapt in my view.
If view models are apt, have a one to one relationship of view models to views.
It may be important to note/remind/point out that with a lot of UI toolkits if the exact same "String" object is referenced twice (both in the model and the view model) then the memory used by the String object itself is not double, it is only a little more (enough to store an extra reference to the String).
(The "View")
The only code in the view should be (the required) to show/hide/rearrange/populate controls for initial view load and (when user is scrolling or clicking show/hide detail buttons etc) showing/hiding parts of the view, and to pass any more significant events to the "rest" of the code. If any text formatting or drawing or similar is required, the view should call the "rest" of the code to do that dirty work.
(The "View Model" revisited)
If the (...facts of which views are showing and...) the values of view fields are to be persistent ie survive app shutdown/restart, the view model is part of the model :--: otherwise it is not.
(The "View" revisited)
The view ensures that the view model is as synch'ed with the view in terms of field changes as is appropriate, which may be very synched (on each character change in a text field) or for example only upon initial form population or when user clicks some "Go" button or requests app shutdown.
(The "Rest")
App start event: Populate the model from SQL/network/files/whatever. If view model persistent, construct views attached to view models, otherwise create initial view model(s) and create initial views attached to them.
On commit after user transaction or on app shutdown event: Send model to SQL/networkl/files/whatever.
Allow the user to ("effectively") edit the view model through the view (whether you should update the view model on the minutest change of a character in a text field or only when the user clicks some "Go" button depends on the particular app you are writing and what is easiest in the UI toolkit you are using).
On some application event: the event handlers look at the data in the view model (new data from the user), update the model as required, create/delete views and view models as required, flush the model / view models as required (to conserve RAM).
When new view must be shown: Populate each viewmodel from the model just after the viewmodel is created. Then create view attached to view model.
(Related issue: what if any data set primarily for display (not editing) should not be entirely loaded into RAM?)
For sets of objects that should not be entirely held in RAM cause of RAM use considerations, create an abstract interface to access information on the overall count of objects and also to access the objects one at a time.
The interface and its "interface consumer" may have to deal with the number of objects being unknown/estimated and/or changing depending on the API source providing the objects. This interface can be the same for the model and the view model.
(Related issue: what if any data set primarily for editing should not be entirely loaded into RAM?)
Use a custom paging system through a slightly different interface. Support modified bits for fields and deleted nits for objects - these kept in the object. Page unused data out to disk. Use encryption if necessary. When editing of set done, iterate it (loading in pages at a time - one page can be say 100 objects) and write all data or only changes in transaction or batch as appropriate.
(Conceptual significance of MVVM?)
Clean platform-agnostic way to allow and lose data changes in views without corrupting model; and to allow only validated data through to the model which remains as the "master" sanitised version of data.
Crucial to understanding the why is that flows from view model to model are conditional on data validation of user input whereas flows in the opposite direction from model to view model are not.
The separation is achieved by placing code that knows about all three (M/V/VM) into a core object responsible for handling application events including startup and shutdown at a high level. This code necessarily references individual fields as well as objects. If it didn't I don't think easy separation of the other objects can be achieved.
In response to your original question, it is a question of degree of interrelationships of validation rules on update of fields in the model.
Models are flat where they can be but with references to submodels, directly for one-to-one relationships or through arrays or other container objects for one-to-many relationships.
If the complexity of validation rules is such that merely validating a successful user form fill or incoming message against a list of field regular expressions and numeric ranges (and checking any objects against a cached or specially fetched copy of relevant reference objects and/or keys) is enough to guarantee that updates to business objects will be 'with integrity', and the rules are tested by the application as part of the event handler, then the model can just have simple getters and setters.
The application may perhaps (best) do this directly in-line in event handlers where the number of rules is so simple.
In some cases it may be better even to put these simple rules in the setters on the model but this validation overhead is then incurred on database load unless you have extra functions for setting without validate. So for simpler data models I tend to keep the validation in application event handlers to avoid writing these extra setters.
But if the rules are more complex either:
(a) a single method taking a special object that is really a composite of the usual business objects containing data for myriad field changes is written for each complex model change, and the method can succeed or fail depending on validation of the rules - facade pattern;
or
(b) a "dry run" / hypothesis / "trial" copy of the model or a subset of the model is created first, setting one property at a time, and then a validation routine run on the copy. If validation is successful, the changes are assimilated into the main model otherwise the data is discarded and an error raised.
The simple getter/setter approach is in my view preferred when analysing each individual transaction unless the vast majority of updates for your app are complex, in which case one can use the facade pattern throughout.
The other way the model ends up getting more complex than a bunch of fields with (possibly) simple getters/setters is if you start "enhancing" classes' getters/setters (with an O2R mapper tool), or adding extra aspects like calls to transaction monitoring APIs, security APIs (to check permissions, for logging etc), accounting APIs, methods that pre-fetch any related data needed for a get or set, or whatever upon get or set. See "aspect-oriented programming" for an exposition on this area.

How do I maintain coherency between model and view-model in MVVM pattern?

Problem Statement
I'm writing a very basic WPF application to alter the contents of a configuration file. The data format is an XML file with a schema. I want to use it as a learning project for MVVM, so I have duly divided the code into
Model: C# classes auto-generated from xsd.exe
View-Model: View-friendly representation of the Model.
View: Xaml and empty code behind
I understand how the View-Model can make View-binding a breeze. However, doesn't that leave the View-Model <-> Model semantics very awkward? Xsd.exe generates C# classes with arrays for multiple XML elements. However, at the V-VM level you need Observable Collections.
Questions:
Does this really mean I have to keep two completely different collection types representing the same data in coherence?
What are the best practices for maintaining coherence between the Model and the View-Model?
I'm not a big expert, but I think that is the case yes. The general idea is indeed to propagate change between the view and the viewModel via Binding, and then between the ViewModel and the Model via events (in the Model -> ViewModel direction) or dependency (in the other direction).
I don't know how standard that is, but my understanding of MVVM is that the ViewModel should hold a reference to the model so that when the user modifies the view, the ViewModel should call the appropriate code on the model. The other way round, the Model should raise events when modified, and the ViewModel should update itself accordingly (the ViewModel being an observer to the model).
#Does this really mean I have to keep two completely different collection types representing the same data in coherence?
I think yes. It's pretty boring, but it works quite well. Hopefully, in the future we will have also a code generator to create the ViewModel part.
Karl is working on that: http://karlshifflett.wordpress.com/mvvm/
You need clearly ObservableCollections at the viewmodel so, yes, you will need two
completely different collection types in the model and in the viewmodel.
I have done an article about doing undo / redo in MVVM where you can find a possible solution to this. It uses what I call the MirrorCollection: an ObservableCollection derived class witch automatically obtains his items from a List (the list of the model).
I think it is an interesting solution, you can find the articles here
Part 1: Using the Viewmodel pattern to provide Undo / Redo in WPF
Part 2: Viewmodelling lists (here is the MirrorCollection definition)
Expose Events or delegates in Model and hook to the same in ViewModel, when ever values in the model changes notify to viewmodel via event or delegates and from Viewmodle you can update the UI.
If you want to update it from view model to model as simple as that just call some method pass the new values

Resources