Is MVVM really useful? - wpf

I have read the MSDN article on MVVM and I am not really convinced.
If the model already implements INotifyPropertyChanged/INotifyCollectionChanged, what's wrong with the View binding directly against the Model?
It seems the extra ModelView introduces some code without much benefit.
Am I missing something?

I was also a bit skeptical about MVVM until I watched this great presentation by Jason Dolinger. I recommend all my co-workers who are starting out in WPF and MVVM to watch it.
Jason started with an application that
one would write in a “traditional”
way, with button clicks handled by
event-handlers in the code-behind that
then updated other parts of the UI.
Using WPF data-binding, Commands, and
Unity, he transformed it, piece by
piece, in a much more manageable,
encapsulated, readable, and testable
M-V-VM design. It was awesome.
To answer your question more directly, even if it seems silly to bind to a ViewModel when your Model already has everything, you'll often wind up needing one little adjustment to the Model that's needed only by the View. Over time, these little changes will creep into your Models, where they don't belong. It'll make your models more complicated than they ought to be.
What I often do when I have a Model that "has it all", is I add a ViewModel that contains one property, the Model. Then in my bindings I just bind to Model.Name, Model.Age, etc. It's really no effort. Later on, if I need tweaks only for the View, I already have my ViewModel class ready. This also makes your code more intuitive and easier to understand. You won't wonder, did I bind to the Model or the ViewModel in this case? It will always be the ViewModel.

INotifyPropertyChanged and INotifyCollectionChanged are not the only aspects to be considered... In many cases, the data exposed by the model will not be easily usable by the view. The role of the ViewModel is to act as an adapter between the model and the view : expose the data in a form that allows the view to easily bind to it, expose commands to which the view can bind in order to perform actions... Typically, a model won't expose ICommands : if it does, then the model is WPF-specific, which is never a good thing is you want to reuse in some other non-WPF application...
I have been using MVVM for a few months, and it made my life much easier : no more "spaghetti code" in code-behind files, clear separation of responsibilities, clean overall architecture...

I have been using MVVM for 2 projects and here are a few things that I have been doing in the ViewModel:
Transforming the data from the model (When you are using a ViewModel, it makes life easier when UI specifications change, you don't need to change the Model/Persistence code)
Implementing a ICollectionView over a collection provided by the model
Implementing Commands
Caching (maintain expensive to calculate data)
Maintaining a dictionary on model data (for fast lookup)
Lazy-loading (not load until it's been used by the View)
Managing Undo/Redo
Validation of data (IDataErrorInfo)
and there is much more to do there (that I forgot) that would not fit in the Model itself, or would make the user interface spaghetti.
Not to forget, the ViewModel enable you to unit test things that you would not be able to test if it was implemented in the UI (such as Commands).
Finally, using MVVM, I was able to build a command-line version of my application very easily by using the ViewModels.

I'm using MVVM with MEF for a few years now and am not really sure how helpful it really is.
In our development we don't reuse ViewModels for different Views, neither do we have designers who are only allowed the change the View (UI).
And a lot of things are hard to achieve in a ViewModel, like setting the cursor focus depending on changes in the ViewModel (yeah, it is possible, but adds a lot of clutter to the code).
The good thing about MVVM is organising the values and commands as bindings instead setting the fields directly, but this could be done without the ViewModel.

Related

Ambiguous between Microsoft Sample and WPF Rules

I thought we should have no reference from View to ViewModel in MVVM Pattern. but just saw an MVVM Sample from code.msdn.microsoft in which ViewModel implements new Window and shows it;
By using MVVM-Light toolkit you use Messenger to Call or Open new Window and Still keep Separate the View and ViewModel form each other. Is it right to reference the View in ViewModel? Or it is wrong;
Do you suggest to call Views Directly from ViewModel for large(or medium) projects?
http://code.msdn.microsoft.com/windowsdesktop/Easy-MVVM-Examples-fb8c409f
YAGNI.
Level of effort and complexity.
MVVM is just a pattern. A pattern you don't have to follow. Any little tool I write for my own use just uses a model, a viewmodel, and a view. The viewmodel exposes all properties I need for the view by INotifyPropertyChanged. The data is moved back and forth from viewmodel to model manually using ViewModel.FromModel(model) syntax. I don't bind to my models. I only use the model when saving/loading data; I don't hang onto it. My views are generated using dataTemplates and dataTemplateSelectors. If I have a property that should change the layout I expose that on the viewmodel and use a selector. Otherwise, I have a datatemplate for every viewmodel object. And it just works.
I call this a form of MVVM, even though it doesn't any toolkit or the exact MVVM pattern that Microsoft describes.
I would personally implement a service to drive commands from the viewmodel to generate new views and hookup the viewmodel. But that's because I have MVC experience, and I think generating views is easier to do using the MVC pattern, whereas desktop views work better using the MVVM pattern.
All my views are composed with contentControls. Setting the content is setting the viewmodel.
So I use a hybrid.
If your software isn't so complex to need the complete Microsoft endorsed MVVM pattern, why create the overhead code IMO. YAGNI.
IMO, having a strong reference from the ViewModel to the View has 2 problems:
It breaks the testability of your ViewModel code. This means you won't be able to Unit Test your code so easily, and if you do you'll have to account for Dispatcher issues and the like.
It makes your ViewModels dependent on WPF assemblies and types. This means you won't be able to literally copy and paste your ViewModels into other applications or platforms such as Xamarin.Android or the like
If none of these are important to you, I don't see any reason why you wouldn't. Not doing so creates additional overhead in your code, by having to implement WindowManagers and whatnot.

Semantically, should Commands and Converters be closer to Views or ViewModels?

I'm wondering if in MVVM I should design Converters and Commands be closer to Views or ViewModels. It's a gray zone for me as they are two types of glue objects bridging the gap between components. Maybe it doesn't really matter, but I'm wondering what Stack Overflow has to say about it.
I used to place Converters in the ViewModel namespace, because they are often reusable even if the View changes. However, I see more and more comments placing them closer to the Views. See top answers to:
Should your ViewModel expose XAML elements as properties or not?
How can WPF Converters be used in an MVVM pattern?
Commands are usually exposed by ViewModels to implement UI events, so I placed them in the ViewModel namespace as well. A classic examples are the RelayCommands. Then I came across an interesting pattern to use Commands to display dialogs between the main view and the ViewModel. I find that just brilliant by its simplicity. The command is really just a proxy, but clearly in UI land. Yay or nay? See:
MVVM and Dialogs
Handling Dialogs in WPF with MVVM
So where do you think Commands and Converters should live in MVVM? View? ViewModel? Doesn't matter?
I don't think you could say they are in one camp or the other. As you said, their purpose is to make the bridge between the ViewModel and the View, while keeping them uncoupled. And in my opinion that's how you should treat them, as glue code.
Converters - you could argue that they are closer to the view because their responsibility is related to how the information is adapted in order to be easily bound and displayed in xaml controls.
Furthermore, you could theoretically use two different converters for the same ViewModel property, depending on how you want to view it.
But nothing is stopping you to use them in other contexts if the need arises, somewhere where the View is not involved at all.
Since your question also implied where to put them, I put my converters separately, not in the views folder, nor in the ViewModels folder, to facilitate reuse.
Commands - are usually exposed by the ViewModel in MVVM, so that can be an argument that they are closer to the ViewModel, but in my experience, they are used most often to facilitate calling logic from the ViewModel via Bindings. If I could bind a ViewModel method call directly in xaml I would not use commands anymore - for simple cases.
Even though they are usually bound to the ViewModel, Commands might also be reusable between Views and ViewModels. If you find yourself copy-pasting the code for commands you can separate them, put the ViewModel behind an interface and reuse them.
Furthermore, the command pattern has many uses outside of the scope of MVVM. (For example, you could use it in the application logic to facilitate "Undo" functionality)
As for where to put them - usually I start by putting them in the ViewModel, and as things get more complicated I move them as needed. Here an interesting post about what you could do as things get complicated: How can I avoid command clutter in the ViewModel?
I know this is a subjective answer, but I hope I have provided some good arguments, and I am open to opinions.

Are the advantages of Model-View-ViewModel (MVVM) pattern worth the overhead?

The question is stated in the subject: are the advantages of Model-View-ViewModel (MVVM) pattern worth the overhead?
In many cases, implementing the view model involves quite significant overhead of duplicating the Model properties and sometimes synchronization between Model and ViewModel data members. For example, currently in Silverlight 4 & WCF RIA, View Models are not generated (if the developer follows the MVVM pattern, it is up to him to create the view models, often duplicating the corresponding Model's properties at ViewModel, that do nothing significant but refer to Model as the storage).
Why not extending the Model class, providing additional properties to make it easy to be consumed by the View instead?
Why not extending the Model class, providing additional properties to make it easy to be consumed by the View instead?
Effectively that is what the PresentationModel is for. Which MVVM is strongly based on. The difference is that the ViewModel is the model for the view and not the model for the data. So you are concerned around more how the view behaves with the data.
If you have a simple UI that all it does is present the model then I would suggest expose the Model on a property of the ViewModel and bind to that. Make sure though the model does implement INotifyPropertyChanged etc.
The power of the ViewModel is when you have things to do in response to a user action. The ViewModel can then support Commands, calling out to services and validation and thus leaving the Model as a data container
Why not extending the Model class, providing additional properties to make it easy to be consumed by the View instead?
In the simple cases, this is all the ViewModel is doing - wrapping up the Model so that its extended in a way that's consumable by the View. If your Model can be bound directly, you're welcome to do so.
That being said, there is more to the ViewModel layer than just wrapping the model - this is also where the application specific logic - ie: the application's plumbing, will occur. Something has to make the requests from the Model classes correctly and compose together the logic.
If you are concerned about extra work, you can always create a ViewModelBase (INotifyPropertyChanged , Errors/Validation, generic stuff) to be inherited by your ViewModel, it will minimize things that you think may cost you time to replicate. And also, Silverlight/Wpf provides us with binding which greatly reduces our coding, besides the fact that XAML also does that by providing functionalities through markup. Besides that you can further the design by using screens, controllers, etc.
For me, I do not see any "overhead" with regards to using MVVM; if there were, it'd be worth it. It properly deals with the Separation of Concerns. It provides a good platform for development especially in teams where people may take care of different aspects of the application without affecting other team members codes (especially between developers and designers).
Hope this helps
Benefits of MVVM
Reduced complexity.
Isolation of Designing and Development.
Dependency injection.
Major advantage is when you have a Well MVVM structured Windows Phone application and want to develop same for Windows Metro Desktop, Only thing u want to concentarte on design as the same view model can be used as it is.
Hope it helps.

What MVVM framework is Good For?

i know some Mvvm Frameworks that introduced in this thread
please describe or give me link for that what are them useful for?
not information about MVVM about MVVM Framework.
thanks :)
i want to know :
What Is MVVM Framework?
I think your question is not really precise. As far as I understand, you ask for the features of each framework?!
You can find detailed information here and here. However, at least one of these links has already been given in the thread you mentioned...
EDIT:
Basically, an MVVM framework is a collection of classes which are commonly used in applications utilising the MVVM (Model-View-ViewModel) pattern. This may include messaging systems to communicate between independent parts of a software, dependency injection techniques, base classes for ViewModels, project/class templates, validation mechanisms, commonly used commands, techniques for displaying dialog boxes, and so on...
To completely understand such a framework, you will have to understand the MVVM pattern first. Because only then (or even only after you did your first MVVM project) you will have an understanding of the problems and/or challenges of this pattern.
To use Mvvm framework just simply follow below steps:
You have a model and a view-model with the same name.
View-models are not supposed to be wrappers around models. The job of a view-model is to broker requests for external services such as the loading and saving of data. The data itself, as well as validation and most of the business logic, should be in the models.
I can’t emphasize this enough. Whenever you create a view-model that wraps a model by delegation you introduce a huge hole in your API. Specially, anything with a direct reference to the model can change a property in such a way that the view-model and thus the UI are never notified. Likewise, any changes to calculated fields in the model won’t be propagated back to the view-model.
You have a view and a view-model with the same name.
Ideally view-models are agnostic to the screens they are used by. This is especially true in a WPF application where multiple windows may be sharing the same instance of a view-model.
For smaller applications such you may only need a single view-model for the whole application. For larger applications you may need one for the main functionality and one for each secondary aspect such as configuration management.
You have no code behind.
In absolute terms code behind is neither a good nor a bad thing. It is merely a place to put logic that is specific to a single view or control. So when I see a view with no code-behind at all I immediately check for the following mistakes:
Does the view-model touch specific controls by name?
Is the view-model being given access to controls via a command parameter?
Is EventToCommand or another leaky behavior being used in place of simple event handler?
EventToCommand from MVVM Light is especially bad because it will prevent controls from being garbage collected after they are removed from the screen.
View-models are listening to property changed notifications
If a model has a longer life-span then the view-model that listens to its events then you probably have a memory leak. Unlike views which have an unloaded event, view-models don’t have a good story for life-cycle management. So if they attach an event to a model that may out-last them then the view-model will be leaked.

Why MVVM and what are it's core benefits? [duplicate]

This question already has answers here:
Why use MVVM? [closed]
(13 answers)
Closed 2 years ago.
Why we go for MVVM over MVC or MVP while dealing with WPF?
What extra benefit we get by using this?
Edit:
To be honest , today I had an interview and I have been asked this question. I answered like INotifyPropertyChanged , ICommand,IValue Convertor.. but he was not satisfied. Henceforth I have put up this question
Thanks in advance
I'll point you to a particularly useful video by Jason Dolinger.
Coming from a WinForms world, implementing any MVX style pattern seemed like more hassle than it was worth but after working with WPF for a couple of years now, I can honestly say that I wouldn't consider anything less. The whole paradigm is supported out-of-the-box.
First off, the key benefit is enabling true separation between the view and model. What that means in real terms is that if/when your model needs to change, it can without the view needing to and vice-versa.
Secondly, while your model may contain all the data you might need in your view, you may want to abstract that data in such a way that your model doesn't support. For example, say your model contains a date property. In the model it can exist solely as a DateTime object but your view might want to present it in a completely different way. Without the viewmodel you'd either have to duplicate the property in the model to support the view or modify the property which could seriously obfuscate the 'model'.
You can also use a viewmodel to aggregate parts of your model that exist in separate classes/libraries to facilitate a more fluent interface for the view to deal with. It's very unlikely that you'll want to work with data in your code in the same way that a user will want to or will want that data presented to them.
On top of that, you get support for automatic two-way data binding between the view and viewmodel.
There really is a whole bunch of extra stuff that I could bang on about but Jason say's it far better that I could so my advice is watch the video. After a few days of working like this, you'll wonder how you ever got by without it.
Good luck.
These are mine specific to MVVM
Increases the "Blendability" of your views (ability to use Expression Blend to design views). This enables a separation of responsibilities on teams that are lucky enough to have a designer and a programmer... each can work independent of the other.
"Lookless" view logic. Views are agnostic from the code that runs behind them, enabling the same view logic to be reused across multiple views or have a view easily retooled or replaced. Seperates concerns between "behavior" and "style".
No duplicated code to update views. In code-behind you will see a lot of calls to "myLabel.Text = newValue" sprinkled everywhere. With MVVM you can be assured the view is updated appropriately just by setting the underlying property and all view side-effects thereof.
Testability. Since your logic is completely agnostic of your view (no "myLabel.Text" references), unit testing is made easy. You can test the behavior of a ViewModel without involving its view. This also enabled test-driven development of view behavior, which is almost impossible using code-behind.
The other two patterns are really sort of separate in terms of the concerns they address. You can use MVVM with MVP and MVC (most good samples out there do some form of this).
In fact, MVP (w/ a Passive View, rather than a Supervising Controller) is really just a variant of MVVM, in my opinion.
WPF has better databinding than any other UI framework, which MVVM would be unruly without
MVVM provides unit testability and excellent view-agnosticism, which make it a good thing to use
Baked in support for ICommand and INotifyPropertyChanged are the two biggest benefits. Using MVVM makes it really easy to wire up the commands and plug data into the WPF UI. Things just work.
I personnaly see MVVM not as a benefit, but as an obligation for those who want to use WPF cool features.
WPF is very very heavily built with data binding at the core, to enable separation of UI from Model. But the way data binding is technically done in WPF is somewhat special, as it's tied to classes like:
DependencyProperty
INotifyPropertyChanged
ObservableCollection
Because of this you just can't really write a model the way you want using standard .NET technology. For example, the WPF TreeView is almost impossible to use w/o using data binding and templates. You just can't populate it simply like you would from a generic model in Winforms for example. It must be bound to a hierarchical model using ObservableCollection to represent a node's children.
So let's say V represents the XAML code and it's code-behind counterpart (so it's tied to WPF as a technology), and let's say M represents your model (so it's not tied to WPF UI technology in anyway).
Well, you'll never have this working properly under WPF with only these V & M.
You must add something between the two. Something that's WPF-compatible and understands your model. Something that speaks DependencyProperty, ObservableCollection and INotifyPropertyChanged. That's what's called VM.
As a side note, an alternative to MVVM is to build a V & M (w/o VM plumbing) combination with M being WPF-compatible but still with a reasonable UI independency. Historically, ObservableCollection was in the WindowsBase.dll assembly (that was shipped with WPF), so it really looked weird to bind a generic model to something tied to a UI technology. It's been moved back to System.dll since. Even then, it's sometimes hard to keep a pure VM model w/o tweaking the M specifically for WPF...
The ability of XAML code to databind, as well as the existance of triggers will break the MVP and MVC Patterns.

Resources