WPF Properties on View Model Interface? - wpf

Using "vanilla" WPF (no MVVM framework like Prism).
Let me say up front that I absolutely advocate coding against abstractions/interfaces vs. implementations whenever possible.
In WPF, when you do your bindings in the view, you are really not coding your bindings against the viewmodel interface. You are really binding against an implementation of the viewmodel/datacontext. I think you could even argue that you are binding against a blank canvas, since the view doesn't really have any knowledge of what it will bind to at runtime.
So is a view model interface that includes every property that the view will bind to a useless abstraction? Should view model interfaces be leaner, only containing methods needed to change state (or handle commands, etc.).
I hope that question makes sense. :)

IMHO, the ViewModel is a Model for the View. 90% of the time, they will likely be 1 to 1... the useful part is moving the logic back into something more testable than XAML. Together, they compose the UI, but the UI behavior is separated from the UI presentation.
Personally, I do not make use of ViewModel interfaces. Between the Command Pattern and the loose binding that WPF and Silverlight use, I don't feel that abstraction would be useful.
I might use ViewModel interfaces in a system where the behavior and View state differed widely based on some business criteria. E.g. if your View was doing driver's license field editing and the fields required varied from state to state, you could make a case for a single, complex view bound to an IStateDriversLicenseViewModel interface. The correct one could be dependency injected based on the state you are working on and could expose properties like IsOrganDonorSectionVisible, to allow the view to reflect the correct changes. However, in this case I suspect a view composed of user controls would lead to fewer problems and less complexity in maintenance.

Abstraction [ie Interface programming] is useful if and only if loose coupling [ie an implementation-agnostic relactionship between consumer and producer] is desired.
Depending on your interpretation of Model View ViewModel [MVVM], tight coupling is permitted.
In practice, the typical scenario I have seen is a tight coupling between View and ViewModel and between View and Model(s). Typical, because Views are designed to fulfil a specific business requirement, ViewModels are tailored to suit the View to facilitate the View's business role.
As Ben Von Handorf suggests, that part of our application that actually adapts the underlying Model(s) to the ViewModel should be separate from our View [at least the declarative Presentation part]. So the adapting is typically captured by a View's implementation of a Command. So, while the declarative aspect of the View has no knowledge of the underlying Model(s) and is loosely coupled, the business implementation, or View's Command, introduces a tight coupling between View and Model. Again, this is cool because the View's sole purpose is to leverage that data in a specific manner as part of its business.
I too am a fan of abstraction, in particular Interface Programming, Dependency Injection [DI], and Inversion of Control [IoC]. However, when tight coupling makes sense, as it does in MVVM, then abstraction is an over-complication.
IMO, the simplicity introduced by tight coupling is what makes MVVM so attractive over its cousins in the Model View Controller [MVC] space.

I think it's generally not sensible to define an interface when you're only ever going to create one class that implements it. That describes every view model class I've ever created. And the view can't use interfaces anyway.
I do sometimes use interfaces in view model classes, but only if I need to define interactions between those classes that don't properly live in the model.

Related

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).

Are current MVVM view model practices a violation of the Single Responsibility Principle?

With current practices (at least with WPF and Silverlight) we see views bound via command bindings in the view model or we at least see view events handled in view models. This appears to be a violation of SRP because the view model doesn't just model the view state, but responds to the view (user). Others have asked how to build view models without violating SRP or asked whether their implementations do so (this last is the controller in MVC, but roughly analogous).
So are current practices a violation of SRP? Or is "view model" really a collection of things that don't violate SRP? To frame this a bit, it seems we need to know what is the single responsibility or if there are multiple responsibilities in the concept, are the individual responsibilities split out, conforming to SRP. I'm not sure.
Wikipedia's definition of view model says
[T]he ViewModel is a “Model of the View” meaning it is an abstraction of the View that also serves in data binding between the View and the Model
This seems good enough for SRP, but then the entry later says (my emphasis added)
[The ViewModel] acts as a data binder/converter that changes Model information into View information and passes commands from the View into the Model
In a Prism blog post about the view model's role, the author says (again, my emphasis)
What it boils down is that the view model is a composite of the following:
an abstraction of the view
commands
value converters
view state
I'm sure I've missed many definitions out there, but they seem to fall into these categories:
Single "vague" responsibility of modeling view state (so what do we
mean by state)
Multiple responsibilities (view state, user interaction (i.e.
commands))
A composite of single specific responsibilities (abstraction,
state, interaction, conversion), thus having a single
responsibility: "managing all that stuff".
If you're curious, I "care" about this because (2) feels right, but seems counter to the prevailing implementations.
Single Responsibility as Martin defines it:
"THERE SHOULD NEVER BE MORE THAN ONE REASON FOR A CLASS TO CHANGE."
A ViewModel, as far as MVVM is concerned is really just a specialized implementation of a Presentation Model.
So while it could be argued that a Presentation Model should only represent the state of the UI, and that a Presenter/Controller should always broker the commands between the UI and the Presentation Model. If one follows this idea, with SRP dividing on State and Commands, then adding a command should not affect the class that represents state. Therefore MVVM would break SRP.
However...
I think this is grasping at straws. MVVM is a fairly specialized implementation used basically in WPF/Silverlight (and now browser clients).
Patterns are designed to make designs simpler where the alternative would be more cumbersome or less maintainable. Since MVVM is designed to take advantage of the extremely rich data binding capabilities of the presentation technologies, then it is a worthwhile trade off.
No! MVVM does not violate SRP, (the programmer does, lol!)
There is no reason that using the MVVM pattern needs to ignore the SRP. MVVM does not mean that there is only one Model Class, one View-Model Class, and one View Class. Certainly, if you only had one View Class, you could only ever show one simple screen.
Those classes that are in the View tier, should be responsible for one thing; doing, deciding, or containing. A View can consist of several sub-views who's jobs are to do certain pieces of the users interractions. Consider a basic form, it has a display grid, items in the grid can be edited, and there is a "Save" button.
The main View would be a container for two other views; the datagrid (a user control, or something) and a command control. The datagrid then is responsible for choosing the right childview to render data in; in essense it's a container that databinds. The View to edit items is a child view of the datagrid, which is in-turn a child of the main View. Lastly the command control is a set of buttons (in this case a single one) who's single responsibility is to raise signals that commands have been issued by the user.
In this way the Edit View (used by the DataGrid) is agnostic about what uses it, and has one responsibility; Same with the command control. Likewise the DataGrid doesn't care about who uses it, only that it can contain the Edit View (child). Nice SRP there.
ViewModels to match the Views (and children) are also responsible for one thing. The Edit View Model is a container to which the Edit View Binds; it simply contains the data fields that can be displayed/edited. It doesn't care about anything but signalling when one of its properties change. The Command Button View Model is a class that does things. It's commands are bound to the buttons, and it will do work based on what the user clicks on. It will have to have access to other parts of the ViewModel(s) to do it's work.
The main page View Model is there to contain the other child views. It's sole responsibility is as an initializer, making all the required ViewModel instances, and passing constructor parameters to other ViewModel instances (say, the Command Button View Model so it knows where to get data for it's work)
It's natural to cram a whole bunch of functionality into a single ViewModel that a large View would bind to. But it doesn't have to be that way, and SRP can be maintained in MVVM.
The main goal of MVVM is to allow for testable design, the Model layer can be tested independantly, all classes in the Model can easily follow SRP. The ViewModel can be tested without the need of a view; it gets trickier to think SRP in the ViewModel, but it is certainly doable; just remember to break out your classes so they only have one concern. The View is bound to parter ViewModels, with any luck, your testing of the ViewModel makes snapping the View(s) on super easy. Remember you can have each View-let adhere to SRP to be part of a larger conglomerate View (container).
TL;DR?
To answer your question directly, the View is a collection of classes that does not break the SRP. Thus, when the ViewModel is abstracted from the View(s) (View-First), they are also a collection of classes that adhere to good SRP.
I consider many of the current practices around MVVM violate SPR (at least). This is yet another situation where simply adding controllers back to MVVM would solve all the problems cleanly. I call it MVCVM :)
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 problem with just using VMs, as you have found, is that eventually you hit cases where they need to know about views, or commands, or other stuff no self-respecting ViewModel should be involved with!
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". The 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.
Simply adding controllers back into the MVVM mix seems to solve all the problems we have found. MVVM is a good thing, but why did they not include controllers? (but this is of course just my opinion) :)
What it boils down is that the view model is a composite of the following:
an abstraction of the view
commands
value converters
view state
I don't see why you've separated the first two items. Commands are part of the view.
As for the rest - you're right. In some cases. I've built applications where the tasks of value conversion and maintaining view state were sufficiently complex that it didn't make sense for a single view model class to do it all, and I broke them out into separate classes that interoperate with the VMs.
So?

MVVM: does change notification muddy the separation between model and viewmodel?

Let's say I have a model which exposes a collection of objects which I will display and change in a GUI.
So we have Model exposing a collection of ModelItem.
The View binds to a ViewModel which exposes an ObservableCollection of ViewModelItem. ViewModelItem is the Viewmodel of ModelItem
The View contains a ListBox and a DataTemplate. the DataTemplate is for items of type ViewModelItem. The View DataContext points at an instance of ViewModel. The ListBox binds to the ObservableCollection.
I control all the code.
So far so simple. Question:
Is it acceptable to expose the collection on the Model as an ObservableCollection? Further, is it acceptable to implement INotifyPropertyChanged on Model and ModelItem?
My concern is I'm muddying the separation between model and viewmodel, but then common sense says, here's a mechanism for notifying changes to elements in my model, lets use it...
Just wanted to get some perspective from others.
Thanks
Short answer:
YES. Use your notification interfaces on your model when you need to notify of changes. Do not worry about muddying your code with this. Be pragmatic.
Long answer:
My philosophy goes like this: When implementing MVVM, bind directly to model objects when there is nothing extra to do. When you need something new (new behavior, properties the view will utilize, etc) then you wrap the model objects in ViewModel objects. A ViewModel that does nothing but delegate data from the model is nothing but extra code. The moment you need to do something to that data past what the model object gives you, you introduce the layer.
So, to extend my thoughts further on that, (and to answer your question more directly), there needs to be a way for the model to tell the ViewModel when something changes. Often, model data is immutable so it doesn't need this notification mechanism, so it isn't necessary. BUT, it is also often the case that the model DOES change. When that happens, the model has two options: use a custom notification method (events, delegates, etc) or use INotifyPropertyChanged.
If you look at the namespace for INotifyPropertyChanged, it is in System.ComponentModel -- not the view -- so I prefer to use it in the model. It is a well-known interface and you can use it to bind directly to your model from your view. No need to implement anything different.
Taking this philosophy one step further, ObservableCollection is in System.Collections.ObjectModel -- also not view-specific -- and it implements System.Collections.Specialized.INotifyCollectionChanged which also is not view-specific. In other words, ObservableCollection was designed to be a collection that notifies its observers of changes. If you have a model that needs to do that, then ObservableCollection is your tool. It just happens to be convenient (not by accident, though) that WPF and Silverlight use these interfaces for data binding.
I guess this is a long-winded way of saying: "YES. Use your notification interfaces on your model when you need to notify of changes. Do not worry about muddying your code with this. Be pragmatic."
It is definitely acceptable to do both. I would even say it's required to do both. Your common sense abilities work just fine. :)
I would only add that if you don't need all the MVVM functionality for your ModelItems, then you can cut some corners by exposing an ObservableCollection<ModelItem> instead of an ObservableCollection<ViewModelItem>, and modifying your DataTemplate to suit. This will save you quite a bit of "preparation" code, so weigh the pros and cons.
It's certainly acceptable to use change notification in the data model if the data model needs change notification. It's also questionable to use change notification in the data model just because the UI needs change notification.
Generally, I design the data model as if there were no UI, and use the view model as an abstraction layer that hides the data model's implementation details from the UI. On the other hand, in a dynamic application it can be the case that the need for change notification is pervasive enough that it just makes more sense to put it in the data model.
No. It's horrible. Your model should not know how it is used. Giving it this knowledge defeats the object of MVVM.
The model should never know it is being used by WPF, winforms, a dos console, as a service or as a lib. If you tell it this, you are going wrong.
It should also be framework independent, not minding if it's part of MVVM, MVC or MXXX!

wpf mvvm confusion

as per my understanding about mvvm is.
there is a model (entity class that also implement inotify...), view (xaml code) and some class as vm (kind of controller which normally inherit icommand) to let us make events/commands to be generated on specific event...
m just wondering about difference between viewmodel class and xaml's code behind class... why don't we simply consider and enhance code behind...
no considerable reason is in my mind to justify this...
or kindly write somethng with example to clear mvvm... and why mvc or mvp is hell for wpf app????
The Model does not implement INotifyPropertyChanged, the ViewModel does. The actual WPF view data-binds to the ViewModel. There is now a lot of documentation online for this.
http://msdn.microsoft.com/en-us/magazine/dd419663.aspx
MVVM is identical to Fowler's
Presentation Model, in that both
patterns feature an abstraction of a
View, which contains a View's state
and behavior.
http://blogs.msdn.com/johngossman/archive/2005/10/08/478683.aspx
In practice however, only a small
subset of application UI can be data
bound directly to the Model,
especially if the Model is a
pre-existing class or data schema over
which the application developer has no
control. The Model is very likely to
have a data types that cannot be
mapped directly to controls. The UI
may want to perform complex operations
that must be implemented in code which
doesn't make sense in our strict
definition of the View but are too
specific to be included in the Model
(or didn't come with the pre-existing
model). Finally we need a place to
put view state such as selection or
modes. The ViewModel is responsible
for these tasks. The term means
"Model of a View", and can be thought
of as abstraction of the view, but it
also provides a specialization of the
Model that the View can use for
data-binding. In this latter role the
ViewModel contains data-transformers
that convert Model types into View
types, and it contains Commands the
View can use to interact with the
Model.
MVVM is associated with WPF because WPF's data binding mechanism when combined with this pattern makes testable GUIs a breeze.
Check this two videos to get some idea. Both videos show developing application starting with everything in code behind and then they refactor to MVVM pattern.
Mike Taulty's series of videos (in fact there is 10 videos in total, check at least first and second)
Jason Dolinger on Model-View-ViewModel
Also, see this SO question for more links: MVVM: Tutorial from start to finish?
why don't we simply consider and enhance code behind...
(In addition to what other have already mentioned:) because it make your code easier to read. In the code behind file, you have UI stuff that is impossible or to complicated to do in XAML. In the view model code file, you have everything related to filling your form with data.
As with all design patterns, blindly following it is not the best idea. For very small windows, MVVM might not make sense. For larger windows, MVVM forces you to make a separation of concerns, which will usually make both your code behind file and your MVVM class easier to read, to understand and to debug.
First, for MVVM purposes you don't need the VM to inherit ICommand. Instead, VM contains a set of properties of type inherited from ICommand. So that View just binds to those properties. F.i.:
<Button Command="{Binding DoSomethingCommand}" />
And code-behind isn't used because it's basically inseparable part of the View. It's the same class your View is. You can't easily test it, and your code is often tightly coupled to the XAML.
And Model is not really obliged to (but can) support INotifyPropertyChanged. Whereas ViewModel should of course implement this interface to allow binding.
I suggest you to read a few introducing articles on the subject. It's not that confusing. This can be the first one: http://msdn.microsoft.com/en-us/magazine/dd419663.aspx
why don't we simply consider and enhance code behind...
Code behind is often (always?) the simplest approach...if you're a developer. But MVVM is designed to assist more than just a developer. MVVM is for the database girl and the graphics guy too.
Separating M (for the db) and V (for the artist) and VM (for you) allows each person to work independently of each other. So, for example, you don't have to wait for the graphics guy to make a UI before you can wire up the db. You can all work in parallel (in theory).
Separation of concerns means separate jobs.

How to build the ViewModel in MVVM not to violate the Single Responsibility Principle?

Robert Martin says: "There should never be more than one reason for a class to change".
Let's consider the ViewModel class which is bound to a View. It is possible (or even probable) that the ViewModel consists of properties that are not really related to each other. For small views the ViewModel may be quite coherent, but while the application gets more complex the ViewModel will expose data that will be subject to change for different and unrelated reasons.
Should we worry about the SRP principle in the case of ViewModel class or not?
The ViewModel single responsibility is to provide the View the information it needs. If the View needs different and unrelated properties that is not important as the ViewModel only has one reason to change and that is the View showing different properties. So you shouldn't worry too much.
That said, if the ViewModel does get huge, maybe you could think about dividing the view into several subviews to improve reusability and keep the Views and the ViewModels manageable.
I agree with gcores.
Once you see ViewModel grow to more than two screenfuls of text, it is time to consider splitting ViewModel into several child models.
Another rule of thumb is that I never have more than two levels of nesting inside XAML file -- if one part of the view becomes too complex, it is time for view refactoring -- extract inner XAML into separate UserControl and create corresponding ViewModel, which will be default data context on child view.
Yes, but that doesn't mean poor design couldn't force you into it.
I agree that splitting your screens into multiple Views with multiple ViewModels is necessary to reduce bloat and complexity. Here's another pattern I've employed to help stick to SRP using MVVM:
Here's one scenario. My ViewModel needs to obtain data and respond to filter commands from the UI. I create the ViewModel to be composite in structure. That is, child classes that have access to private members of the ViewModel perform linear tasks such as handling the filtering. I might also have another child class that performs the necessary logic for selection of items based on criteria. You get the idea. Once the ViewModel is performing certain functions that span across several methods, it may be a good candidate to delegate to a child class. The child classes remain part of the main ViewModel, so it's just a way of reducing the size of the ViewModel and makes unit testing these linear operations easier.

Resources