My name is Jesús from Spain, I'm a .NET developer and I just discovered this great web few days ago.
I have some questions about the MVVM pattern and I will be glad if you can answer them.
I started using WPF three months ago and I've learned the MVP pattern.
MVP is so good because you can structure the application so well.
I started seeing MVVM everywhere, but everyone is using the pattern by his own method.
Every blogger is talking about MVVM in their WPF's blogs but every implementation is distinct.
I'm focused now with the implementations that use the MVVM toolkit on CodePlex, but I have questions and I can't find too much information.
I think that MVVM is a variation of MVP.
With MVP every view has a presenter that does the view's job.
In MVVM it's the same thing but using commands whenever you can.
I also saw that if you need an event, it's like with MVP; delegating the event to the presenter / View-Model, that is if it's not a job for the view (such as updating the UI).
On the other hand, the View-Model doesn't has a View reference so I have to play harder with data-bindings.
You have to use the DelegateCommands (that are the same thing as RelayCommands, right?).
Uhm... more questions... Is it safe to use the same View-Model with two views / user-controls?
Oh... I ran into a problem yesterday when I was playing MVVM.
I created a CommandReference of my command for the key-binding thing and I assigned this reference to the command property of my button, well, the CanExecuted worked the first time but it didn't update the IsEnabled property when the CanExecuted was true. I fixed it by binding the command directly to the button and not using the reference. The question is: Why some code is linking the reference to the objects and why other code is binding the command directly?
What things related with MVVM should I learn? (I saw something called attached behaviors yesterday but I don't know what is that).
I'm rewriting a note tacking app that I developed using MVP but now with the MVVM. I will replace the events with commands (using the DelegateCommand), eliminate the views references on the View-Model and I think that's all because the examples that I saw of MVVM is much like MVP.
Well, I will appreciate if you point me to all the misunderstandings that I have with this pattern.
Thank you and in the future I will help the next MVVM novices :)
Wow, I'm going to try to answer as many of your questions, that don't involve a specific technology or framework, as possible... sorry if I miss some (bullet points would help)
MVVM is not necessarily a variation of MVP. MVP itself is an ambiguous, loaded term. Martin Fowler did it justice by splitting it into two patterns. MVVM stands on its own, but shares some concepts with the MVP patterns. Like all UI patterns, it seeks to separate view logic from business logic as much as possible. What the MVVM does that is different from MVP is it creates a model purely for the purpose of presentation (or a presentation model). This is different than how MVP patterns solve the separation problem.
Passive View - With the passive view, the view never sees the model.
Supervising Controller - MVVM is much closer to the Supervising Controller pattern than to the Passive View. The only real difference here could be that the MVVM explicitly creates a model just for the view (hence the term "View Model")
The ViewModel doesn't have a reference to the view, because it serves as a model for the data of the view. This is an appropriate abstraction. If it also referenced the view, you would have a two-way dependency which would create additional coupling. Also, the ViewModel itself doesn't have a real reason to be aware of the View. Its only job is to abstract the model (the actual business model) from the view.
DelegateCommands vs. RelayCommands - I believe you're getting technology specific here, so I can't really answer that one well.
You should not design a ViewModel for more than one view. This only creates coplexity inasmuch as if you change a view, you will have to investigate which ViewModels might be affected and change those. This could possibly lead to a cascade effect. Your behavior should be in the business model, not the ViewModel, so the ViewModel need only contain translation and event handling logic.
It would be a good idea, however, to have a 1:1 ratio of ViewModel to UserControl, since UserControls are supposed to be able to act as autonomous units on your screen.
As for the other technology specific questions, sorry, I have no answer. I can suggest, however, that you carefully read the links I included for the Passive View, Supervising Controller, and Presentation Model. The provide some context to UI patterns, and are technology neutral.
It's important to keep in mind that, while MVVM is suited to solving problems posed by adopting WPF, it is not a technology specific pattern. If you dive too deeply into a specific implementation without understanding the underlying philosophy, you could make some very big mistakes early on, and only discover them after it's too late. Unfortunately, MVVM is not a well documented pattern, and you are right when you stated that everyone has their own idea of what it is.
It's not a revolutionary pattern (it has been around for years under different names), but the data binding of WPF makes it a viable solution now, and so it's enjoying newfound popularity. It's a good pattern, but it's not doctrine. Approach every "dictate" you're faced with with the appropriate amount of skepticism.
EDIT
#micahtan is right when stating that data bind is a very important piece in WPF. I stated that WPF's data binding enables the MVVM solution, but the binding itself is very powerful, which is why adoption of MVVM is growing faster than the literature surrounding it.
You don't actually have to use the RelayCommand. All you really need to do is implement the ICommand interface on an object. In the SoapBox Core framework I defined an interface called ICommandControl and all button ViewModels, etc. implement that. There's also an AbstractCommandControl class you can derive from to implement it.
Related
I have some doubts in viewmodel pattern. My doubt is about, why we don't use UI elements in viewmodel. If we use UI elements in viewmodel what will happen like any performance issue?. Please give any suggestion.
You do not use UIElements in ViewModels, since the MVVM principle defines UIElements to reside in the View. The correct placement of UIElements, is defined by John Gossman, in the article Introduction to Model/View/ViewModel pattern for building WPF apps:
The View in Model/View/ViewModel consists of the visual elements, the buttons, windows, graphics and more complex controls of a GUI.
You do not use UIElements in the ViewModel of an MVVM application, for at least two reasons:
When later porting the application to another UI framework, it is much easier if all UI related code is just in one module, namely the View. Porting would be much harder if UI code would be spread across the View and the ViewModel.
Unit testing is much easier if all UI related code is just in the View.
The latter reason, of course, is the most important, for most developers. Josh Smith, the father of WPF-MVVM puts it like this in his article Patterns - WPF Apps With The Model-View-ViewModel Design Pattern:
If you can write unit tests for the ViewModel without creating any UI objects, you can also completely skin the ViewModel because it has no dependencies on specific visual elements.
UIElements are troublesome for unit tests, because WPF UIElements need a layout-measure-render loop for working correctly. In unit tests, however, you usually do not have such a loop.
I am implementing a Diagram/Flow-Chart type designer using a Model-View-Presenter (MVP) pattern in WPF.
I have often though of this pattern (and some of the others such as Passive View and MVVM) as high level architectures that fail to address some of the complexity involved in rich UIs (here come the SO trolls).
In my particular instance, I have a UI which resembles the following mockup:
I have made the choice to use Presenter objects for each element which requires presentation logic on the designer. This has left me with the following designers thus far.
DesignerPresenter
ControlPresenter
ControlOverlayPresenter
ConnectionPresenter
ConnectionPointPresenter
OverlayPresenter
The reason I have implemented each of these is because each of them needs to handle presentation logic and communicate its actions to the business/domain tier separately in order to avoid bloat (IMO).
The only other way I would see doing this is if there was one presenter that handles all this presentation logic which seems like it would get out of control very quickly.
My question(s) are as follows:
Is it common to see presenter provided for each UI element on the screen such as I am doing in order to allow for separation of the presentation logic?
Some of the presenters that are created are logically child presenters (The ControlPresenter is a child presenter of the DesignerPresenter) Is this normal?
Is this in alignment with another pattern that makes more sense?
I never used the MVP but I'm really comfortable with the MVVM pattern and if I replace the word Presenter with ViewModel the design fits with what I would really do.
It is completely normal that the DesignerPresenter has an ObservableCollection of ControlPresenter and that the ControlPresenter contains an ObservableCollection of ConnectionPresenter. The ConnectionPresenter will probably have two ConnectionPointPresenter as well.
The overall design seems ok but there are probably other similar architectures that would fit too. IMHO maybe there is too much separation. Makes sense to separate a connection and the connection points?
Recently i got explained that MVVM can only be done "the right way" if i use DataTemplates. Is this truely the case?
I'd say its a good idea to use DataTemplates if you want highly reusable "Views".
But if i am going to develop an application that has, say, five to ten different pages, and there is very little to none reuse of specific controls (like the "Person" view is only used once, and its highly likely that this requirement doenst change), why cant i simply create a usercontrol and put that directly into the code?
Am i missing some important core principle of MVVM here?
Main selling point of MVVM is separation of View from the ViewModel (so that VM doesnt know about View) by using powerful Binding feature of WPF.
DataTemplates are a just another feature which allows you to represent data in different way. As you have said, if you dont have reusable DataTemplate then dont create one, even if you do make sure it resides in the View's Resources, you can share it wider group if you wanted do.
using UserControl can be useful where you need to do something extra (apart from simple representing data), for example, some complex validation or extra commands/buttons
I dont think MVVM and DataTemplates are related in the same context.
There is no special needing for DataTemplate, you have a view and a viewmodel that cooperates with databindings and events. The MVVM goal in WPF is to remove the code from the view to achieve a real presentation only view, and not a messy code behind store. Having the ViewModel agnostic from the view is another goal, even if not always achieved.
I have an example with a bunch of logic in my GUI class (winforms). I am going to refactor that so that there is no logic in the gui and a separate class holds all the logic.
What is that pattern? Say I had a form class called AddAddressForm, what would you call the associated file that holds the logic? AddAddressMediator (doesn't quite fit that pattern), if I was doing WPF I would call it the ViewModel (but I am not).
Sounds something like model-view-controller without the model part.
I don't think its called anything. I've tried doing that sort of thing in the past with Windows Forms, but unfortunately it didn't really work:
For each form I had another class called something like MyFormLogic that supposedly contained all of my logic for the form, with the form itself just containing a load of methods and events for manipulating the form (things like an AddButtonClicked event, and a AllItems collection property)
It seemed like a brilliant idea at the time (Yay easy unit testing!), but what actually happened is the MyFormLogic class became just as big and messy as before, and now I had a whole lot of extra pointless code exposing the extra methods events in my actual form class. (Also creating an instance of forms was a pain)
I'd recommend that instead you work on refactoring out as much logic as possible into lots of smaller classes that do 1 thing, rather than 1 extra class which deals with all forms logic (Its difficult to explain what I mean without some examples)
By the example given , it seems that your object shares some kind of common data.
Look at the Flyweight Pattern then.
I believe it is called Model-View-Presenter pattern. although it is commonly used in asp.net, it should be applied to WinForm as well.
http://msdn.microsoft.com/en-us/magazine/cc188690.aspx
Martin Fowler splits original MVP pattern into 2 patterns , Supervising Controller and Passive View, But I still like its original name , MVP.
it depends type of logic , say you have Conditonal Logic and you create different object from it , so seprating this in a new class will be pointing to Factory Method.
2- If you have complex algorithms in your class and you seprate it another class/s , you most probably using Strategy Pattern.
lot of other combinations also possible.
It's Model-View-Controller (MVC). In your example, the Model is the Address, the View is the dialog, and the Controller just mediates events from the dialog to the Address object.
Note: you may omit the Controller for really simple situations, but don't if you ever want automated unit-tests; the separation (via interfaces) will pay off.
I believe this is called Humble View.
For more details and different takes on it, see the Humble View section of the GUI Architectures page on martinfowler.com.
What you describe is still the Model-View-ViewModel pattern, which isn't specific to WPF. The core tenet is that the ViewModel contains state and logic, and the View constantly synchronizes itself with the ViewModel. This is nice and easy with WPF bindings, but they aren't a prerequisite; any stateful UI can utilize MVVM. The Forms flavor of the pattern can get quite wordy on the view side.
Sounds like your basic separation of concerns by breaking out the view and functionality into different files. Not really sure if it really falls under any sort of pattern per say, but it does remind me of web forms a liitle bit with the views and code behinds.
As I am further digging into MVVM and MVVM-light I recognized, that there is no MVVM-light provided base class for models.
But from my understanding, messaging and raising notifications could also happen in a model. At least in communication between models I would find that messaging would come in very handy.
So I just decided to derive my Model from ViewModelBase, even though some of the properties (like the design time ones) will be unused.
But the more I am looking at this, the more I think I have missed something. Is it considered "bad practice" to derive my Models from ViewModelBase?
And is it ok to use Messaging for Model communication?
Derive your view-model classes from whatever you like... MVVM-light offers the VieWModelBase to provide an implementation of ICleanUp - which is good for managing the life-cycle of ViewModel objects. My own choice has been to implement all scaffolding for Property Change notifications in a base class, then derive from that for model classes. About the only strong suggestions I have regarding model classes are:
Once size doesn't fit all. How you store your data may be different from how you interact with data, and ViewModel objects should be geared towards supporting interaction, not storage, and if you need to interact with the same data (Model) in two very different ways, then design two different ViewModels to support these different interactions.
Do use attributes (a la System.ComponentModel) to annotate the models. You can get a lot of your validation work done this way - and validation feedback is the responsibility of the presentation layer (View + ViewModel), not the problem domain (i.e. the Model).
Really good ViewModel classes are also usually stateless enough that they can be recycled/reused within a single user interaction, such that large data lists can be virtualized (WPF supports virtualization) to save RAM.
Remember DRY (Do Not Repeat Yourself), KISS (Keep It Simple, Stupid!) and YAGNI (You ain't gonna need it) - are the principles you should keep in mind above any academic design principles. I've litereally wasted weeks on a WPF app implementing academically perfect MVC/MVVM patterns, only to find that they detracted form the overall understandability of the finished solution. So... keep it simple! :)
I would take a look at the EventAggregator in the Composite Application Library. The answer in this post has a good description of it. Jeremy Miller's post goes into a bit more detail.