I am new to MVVM and now doing some MVVM refactorying work on a silverlight project, suppose it is a book shopping application.
The View is a book list, I bind the title of the books to the ViewModel. So I have a public string Title { get; set; } in ViewModel, also a public string Title { get; set; } in Model (am I right?)
Now I want put a event handler to update the book title, should I put the event handler in ViewModel or Model? and what is the Model used for?
In my opinion "Neither"... Add controller classes to the mix of MVVM instead.
The problem with putting controller code in view models is that is makes them harder to test independantly. In many ways I see this as just as bad as code behind.
It seems to me that everyone assumes MVVM has no controllers as they left out the C. MVVM is really a variation of MVC "that just adds ViewModels".
Maybe it should have been called MVCVM instead?
ViewModels are only there to offload the "GUI" code from the view and to contain any data for binding. ViewModels should not do any processing. A good test is that your ViewModel is testable via automated unit tests and has no dependencies on data sources etc. They should have no idea where the data is actually coming from (or who is displaying it).
Although it can be overlooked/avoided, a Controller should be responsible for deciding what data model to display and in which views. The ViewModel is a bridge between Models (the M in MVVM) and Views. This allows simpler "separated" XAML authoring.
The pattern we are using successfully on all recent projects is to register controllers only, in modules, and initialise them at startup. The controllers are very light/slim and the only thing that needs to hang around for the life of the app listening for, or sending, messages. In their initialise methods they then register anything they need to own (views and viewmodels etc). This lightweight logic-only-in-memory pattern makes for slimmer apps too (e.g. better for WP7).
The basic rules we follow are:
Controllers make decisions based on events
Controllers fetch data and place it in appropriate View Model properties
Controllers set ICommand properties of View Models to intercept
events
Controllers make views appear (if not implied elsewhere)
View Models are "dumb". They hold data for binding and nothing else
Views know they display a certain shape of data, but have no idea
where it comes from
The last two points are the ones you should never break or separation of concerns goes out the window.
In simplest terms, the Model is the 'real' underlying data model - containing all the info for the booklist that might be needed by the application, able to get and set data from your database.
The ViewModel is an object that exists primarily to provide data binding for your View. It might be a subset of the Model, or it might combine properties from multiple Models into a single object. It should contain the necessary and sufficient properties to allow the View to do its job.
If the event handler relates to the View, then it belongs in the ViewModel. You might try using the Command Pattern (see Custom WPF command pattern example) if it fits your purpose.
Related
Okay, so I am working with Microsoft Prism in WPF using a MVVMC(or MVCVM) pattern.
In my ChatModule I have a series of Views, ViewModels, and one Controller.
For the Views I have
ChatAreaView - Displays the chat messages that come in to be read. This is hosted inside of a TabControl region so that I can have chat windows between the user and other users, or maybe file transfer windows, etc.
UserAreaView - This is a list of the users. Right clicking has context menu to interact with them... like sending a file or whispering.
MessageAreaView - This is where the user types in messages to be sent to all of the others.
For each view, I have a corresponding ViewModel. ChatAreaViewModel, UserAreaViewModel and MessageAreaViewModel. These ViewModels essentially only contain properties.
For example, the UserAreaViewModel defines a struct of type User which is essentially just a Name. Actually this is defined outside of the class, but still... it uses it. It has an ObservableCollection to store a list of all the Users who are currently connected. It also has ICommand properties defined to interact with the user. Right now I have SendFile, Whisper and Nudge... with intent on adding more in the future.
The Controller creates these views and ViewModels, and marriages them. It news them up, assigns the ViewModel as the corresponding View's DataContext, and sets all the initial properties of the ViewModel. Over the lifetime of the module, it will react to user interaction and execute DelegateCommands that it has assigned to each of the ViewModel's ICommand properties. These will further alter the state of the properties in a ViewModel.
I am using the actual types of Views and ViewModels, instead of interfaces, like such.
#region Views
ChatAreaView viewChatArea;
UserListView viewUserArea;
MessageView viewMessageArea;
LoginPromptView viewLoginPrompt;
#endregion
#region ViewModels
ChatAreaViewModel viewModelChatArea;
UserAreaViewModel viewModelUserArea;
MessageAreaViewModel viewModelMessageArea;
LoginPromptViewModel viewModelLoginPrompt;
#endregion
Would things be a lot more neat, less coupled if I defined interfaces for the Views and ViewModels, and operated on these interfaces within the controller instead of the concrete implementations? Could I then just register them with my Container in the Module class(which is essentially the root of each Module)?
What do I have to gain from doing this? How would I implement an interface for each view to distinguish them from the others? They don't really do ANYTHING except have XAML... and teh ViewModel's don't really do anything either except have certain properties. And those properties might be subject to change. On the UserAreaViewModel for instance, I will definitely want to add more commands so a user can interact with another user in different ways.
Can somebody help me out here? In my mind I'm thinking I should be abstracting this stuff, but I don't really know a logical way I should be going about it, or even if it's a wise idea to do so. What do I have to gain?
Thank you for your time. The below image is an example of what I'm working on. Ignore the Add new Item button and the styling of everything... that's not what I'm working on right now.
loosely coupled - can replace an entire class with altogether different implementation in future.
independent development.. can inject a dummy UI / view until final UI gets ready. two pieces can evolve at the same time (after having a common contract).
no need to add references to the modules (implementing the view). can use ConfigurationModuleCatalog to discover types from config file.
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).
I was trying to use MVVM design pattern with WPF and Entity Framework to create a simple application. All goes well and good if the classes are loosely coupled, but if I have sth. like two model classes : Customer and Address and a Customer has a collection of Addresses.
Now for those classes I need to create two VM classes - CustomerVM and AddressVM. CustomerVM should have ObservableCollection of AddressVM objects. Every change made to those VM classes(which includes all CRUD operations on both CustomerVM and AddressVM) needs to be reflected in the model classes - which is why I end up writing a looot of code that eg. subscribes to the changed event of ObservableCollection and if a new object is added then add a new object to the model ... and so on ...
What to do with this? Is this usual while using MVVM? Am I doing everything ok? How to cut down the amount of code needed for such a simple class hierarchy? Are there any frameworks that can create basic VM classes that "behave well" with other classes in hierarchy? What to do if class relationships get MORE complex?
OR TO PUT IT SIMPLE:
How to reflect changes done in vm collections in model collections :
CustomerVM1.AdressesVM.Add(new AddressVM{City="New York"})
should cause an equivalent of:
Customer1.Adresses.Add(new Address{City="New York"})
There's also the same problem the other way round - how to reflect changes done to collections in model to be included in the view model, but I'm more interested in the first one, because it has a more practical application and vm objects can in most cases be simply recreated.
You might be interested in the BookLibrary sample application of the WPF Application Framework (WAF). It shows how to use the Entity Framework and MVVM together.
Short hint: It doesn't create a wrapper ViewModel for every Entity class. Instead, it creates the ViewModel classes for the Views.
You're running into exactly the same problem I ran into when trying to figure out how to keep an ObservableCollection in my ViewModel sync'd with a plain-old-collection in my Model. An ObservableCollection is wonderful because the View can bind to it and automatically change when the collection changes. Unfortunately you've just moved the problem of sync down one level.
One option is to use ObservableCollections everywhere, even in the Model. This isn't very clean architecture because MVVM isn't supposed to make any demands on the Model.
What I did to solve it was to introduce a Presenter, so my architecture looks like this:
View -> ViewModel <-> Presenter <-> Model
Also, I made my ViewModels dumb. Here's how a typical user action takes place from initiation to completion:
User clicks the Add button
ViewModel either raises an event that the Presenter subscribes to, or calls a method on the presenter, or just calls a callback that the Presenter provided to the ViewModel when the ViewModel was constructed. Essentially it delegates the action to the Presenter.
The Presenter calls Add on the Model.
The Model reacts to the Add call, updating all of it's relevant state, including the plain-old-collection.
The presenter, having executed the action on the model, then reads the new state from the Model and writes the state into the ViewModel. Binding takes care of synchronizing the View.
So in your case, the Presenter could subscribe to a CollectionChanged event on the ObservableCollection in the ViewModel, and when it changes, it reacts to the event by calling Add on the Model. On the other hand, when the Presenter is processing some other user action that calls Add on the Model (it knows because it handles all interaction with the Model), then it knows that it has to propagate that change to the ObservableCollection in the ViewModel.
In my code, I simplified the situation... after every user action is executed on the Model by the Presenter, I do a straight copy of all relevant state in the Model to the applicable place in the ViewModel. You're doing a little more work than you need to, but in a typical CRUD type of application, there's no noticeable performance issue. If I have a really big collection of objects, performance could be a problem, and there I drop down to a more fine-grained synchronization (updating only the changed entity), at the expense of more complicated logic.
As I wrap my head around the mvvm thing, the view is the view, and the viewmodel is 'a modal of a view' and the model are the entities we are dealing with (or at least that is my understanding). But I'm unclear as to what and when the model entities are populated. So for example:
Lets say I have app that needs to create a new record in a DB. And that record should have default values to start with. Who is responsible for the new record, and getting the default values. Does this have anything to do with MVVM or is that part of a data access layer? Who calls the the viewmodel?
Or for existing records when\where are the records retrieved? And saved if altered?
Thanks
In an overly simplified answer, your ViewModel should contain the LOGIC for controlling what your View displays, as well as how it is allowed to interact with the Model or Data.
Events like Getting data, Saving and Deleting are intercepted through a Command mechanism and pushed into the ViewModel, where they can be tested. Handling 'Dirty' events are also the duty of the ViewModel. As for who Calls the ViewModel, you are entrusting the Calling to the Binding mechanisms available within WPF and Silverlight.
Within the ViewModel it is still about staying with best practices and ensuring that you have a DataAccess layer abstracting your Data Source and possibly using the Repository pattern to abstract that.
The life cycle of a ViewModel could be as simple as the following...
Constructor called by View
GetData method called by ViewModel Ctor
Data received and pushed into existing View databound ObservableCollection property
However since you will probably have a lot of moving parts within the Ctor of the VM, including the Data Repositories Interface you will probably want to work with an IoC. This will make the life cycle of the ViewModel closer to...
View/ViewModel (Depends if you are View or ViewModel first) is pulled out of the IoC
IoC Handles the pairing of the View-ViewModel (Convention based)
Data Repository is Injected into the ViewModel
GetData method called by ViewModel Ctor
Data received and pushed into existing View databound ObservableCollection property
This may seem like more steps, however with an IoC container you are really just calling a single method like IoC.Get(), and the rest of the steps are wired up automatically based on the conventions applied.
I use view-models to control loading (with defaults) and saving my models, and to create collections and objects that I use to bind to my views. This includes setting default values on my models.
State and Bahavior of your view is define in your viewmodel which means all events are declared here.
Who calls the the viewmodel?
it depends who needs it. you can call it in your view.
for existing records when\where are the records retrieved? And saved if altered?
saving and retrieving part is in your viewmodel.
For detailed explanation, visit this site.
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