How do Behaviors and ViewModels relate in MVVM? - wpf

So I stumbled upon a problem while learning MVVM. I had a TreeView that contained TextBlocks which I wanted to perform an action on when I double clicked any of the TextBlocks in the TreeView. I started to learn about Behaviors, and I have a great example of how a behavior is implemented but the example does not connect the Behavior to a ViewModel at all. So in other words, if I double click on the TextBlock, I have the Behavior class that catches it but I don't have any ViewModel to perform any actions.
Could someone take a moment and explain how these tie in? I was reviewing this article:
http://msdn.microsoft.com/en-us/library/gg430869(v=pandp.40).aspx
But I didn't seem to grasp what I was looking for.

MVVM concept provide us a decoupling mechanism in WPF application which means no more code in xaml.cs file. Attached behavior is different thing. It has not relation with MVVM.
But because if we have scenarios where I cant use MVVM e.g. Select the text of TextBox on double click. Which is a behavior you want to add on textbox.
You will prefer implement the double click functionality in xaml.cs file as it not reusable and also tightly coupled.
This is where behavior come into picture. We will create the behavior for TextBox and will attach it. Now you can attach this behavior to as many controls you want.
EDIT:
if you are using WPF 4.5. you can look Markup Extensions for events
If you want to do it with attached behavior. Create an attached behavior of double click event which has Command dependency property. Your double click behavior just raise the command attached and in xaml bind the command with viewmodel which I expect you know how.
Hope, I am able to answer you comment.

D J has a good answer, though I'd like to insert some additional thoughts to this discussion.
In my experience, view behaviors (whether code-behind, attached behaviors, blend behaviors, or custom control logic) are often useful when the view does not depend on a view-model to function properly. If a view (UserControl, Window, Page, etc.) does not logically make sense in the absence of a view-model, it might make more sense to remove behavior from the view and move it to the view-model.
While we can do pretty much anything under the sun with all types of behaviors, it is often not wise to. MVVM, for good reason, limits what we should do so that we can observe separation of concerns to improve our application's cohesiveness and to decouple our classes. These two things are what software maintainability is all about, and these concepts become increasingly important as the application grows into enterprise software.
It is important to think about the concerns that the behavior has. Understanding this will help us find a properly suited place for it. Here are some questions to help know where it belongs:
Does the behavior interact with a business domain model (this is the first 'M' in MVVM)?
Behavior that has a dependency (even a loosely coupled one) on a domain model should likely belong in the view-model (or service), and not in the view. For instance, if the behavior needs to save to or read from an external device (e.g. a database), it has a dependency that the view should never have. Wrap this logic in a service function.
Or if not using a heavily layered architecture, put this inside of a view-model.
Does the behavior interact with application services, domain services, infrastructure services, etc.?
For the same reasons as the prior answer, the behavior likely belongs in the view-model or a service class. The view should have no explicit knowledge of services or domain model objects as it would muddy up its responsibilities (or concerns) that the view has. A view should only be concerned the visual/physical aspect of the user UI. Many views should define a contract (i.e. a view-model interface) that it binds to in order to operate correctly.
Will the behavior need to be reused across different views of the same kind?
This is a bit of a tricky question. Many times we foresee being able to have a different presentation for the same content. In effect, the view in these cases is a thin wrapper around some structure. For instance, suppose for a e-mail application we have a summarized view for received e-mails as well as a detailed view. Both views might need to support the same behavior (e.g. delete, reply, forward). Because we are reusing the behavior across different views of the same kind, then the behavior should belong in a common, reusable place. View-model logic is a good place for this.
Will the behavior need to be reused across views of different kinds?
When the behavior needs to be reused across different kinds of views (e.g. TextBox, ComboBox), we likely need an attached behavior. Usually, we can know this because the views are so diverse that it is not possible for them to share a view-model interface. Given that the behavior is concerned with view-related responsibilities, then custom control logic, code-behind, attached behaviors, or blend behaviors are all suitable places.

Related

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.

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.

Attach Behaviour Vs Routed Command

What is difference between the two, i am just confused so much on these two concepts and not able to apply correctly?
Attached behaviors is a way of extending controls without having to subclass them! Examples of this is add watermarks to textboxes, forcing textboxes to only accept certain charecters, etc... It is typical stuff that you can do to a control by subscribing to certain events or setting properties! By creating a attached behavior, you are just encapsulating that functionalaty for reuse!
Routed Commands is a way of abstracting away your executing logic for actions like clicking on a button... in WPF, the build in implementation of ICommand, basically walks the visual tree looking for a RoutedCommand that it can execute! The real big diference between these too is that ICommand can only really work on things like buttons... If you need to execute some logic on clicking of a image, you can't without creating a attached behaviour!
Also read up on RelayCommand/DelegateCommand
UPDATE
Attaching a behavior to an object simply means making the object do something that it would not do on its own.
Josh Smith - http://www.codeproject.com/KB/WPF/AttachedBehaviors.aspx
In search of a similar question, I came across Chapter 6 of the PRISM 5.0 Handbook, which states as a note on command-enabled controls versus behaviors:
WPF controls that support commands allow you to declaratively hook up a control to a command. These controls will invoke the specified command when the user interacts with the control in a specific way. For example, for a Button control, the command will be invoked when the user clicks the button. This event associated with the command is fixed and cannot be changed.
Behaviors also allow you to hook up a control to a command in a declarative fashion. However, behaviors can be associated with a range of events raised by the control, and they can be used to conditionally invoke an associated command object or a command method in the view model. In other words, behaviors can address many of the same scenarios as command-enabled controls, and they may provide a greater degree of flexibility and control.
You will need to choose when to use command-enabled controls and when to use behaviors, as well as which kind of behavior to use. If you prefer to use a single mechanism to associate controls in the view with functionality in the view model or for consistency, you might consider using behaviors, even for controls that inherently support commands.
If you only need to use command-enabled controls to invoke commands on the view model, and if you are happy with the default events to invoke the command, behaviors may not be required. Similarly, if your developers or UI designers will not be using Blend for Visual Studio 2013, you may favor command-enabled controls (or custom attached behaviors) because of the additional syntax required for Blend behaviors.
For me, this is the single best summary of what’s the difference between behaviors and commands.

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.

Should I Keep Business Objects Separate from the UI in WPF?

WPF's view model oriented way of doing things makes it very tempting to just use business objects in the UI. Have you seen any issues with this? Why or why wouldn't you do this?
The guidance from Microsoft's product teams (e.g., that's what the Blend team is using) is the Model-View-ViewModel architecture, a variant of the popular MVC pattern. A good starting point is http://blogs.msdn.com/johngossman/archive/2005/10/08/478683.aspx. There are also good articles by Dr. WPF on this topic.
Essentially, they advocate to create a ViewModel layer which uses binding-friendly business objects, such as ObservableCollection and the like.
Also, if you might eventually move to Silverlight 2, you might want to keep the business objects out of the UI layer so you can swap out UI technology (until WPF and Silverlight become source-code compatible).
I guess I see it in a different light. I try to keep as much out of the UI as possible so I can use whichever UI presentation I need (ie. web, WPF, WinForms). The more business logic in the presentation layer, the more you may have to rewrite later if you migrate towards a different UI.
It's not a problem having business objects in the UI, as long as all you're doing is viewing them. In other words, if you want to change the properties of one, or delete one, or create a new one, you should be sending a message to the controller, presenter, or whatever to do that; and the results should then be updated in the view.
What you shouldn't do is use the ToString method of your objects (or any other methods or properties on your objects) to affect how they'll appear in the view. You should use DataTemplates to represent the view of your objects. If you need a more complex representation, you can use an IValueConverter to change the object into its visual representation.
Not being a WPF guru, I can't be sure, but the usual reason for separating your M, V and C is so you can test the controller independent of the view, and the other way around.
Nothing stopping you, of course, but it should be a lot more testable (ie, unit tests) if it's separate. The MVP pattern, which is usually the one that MS promotes, is more geared around the presenter (ie, your WPF form) having more control, and thats fine too....
Depending on your application architecture or the on the way you are planning to reuse your components and objects, you can choose a certain degree of independence from the user interface (in this case WPF).
Here is a sample of my experience:
I've worked with WPF just a little, on
a relatively small project, where the
business layer was already defined,
and we just needed to create a user
interface. Of course, the interface
had defined it's own rules and objects
that it was working with, and because
the application was defined just for
UX we have chosen to create our own
specific objects, mostly by extending
DependencyObject (mainly for Data
Binding purposes).
Some people may argue that it's not ok
to use dependency objects because they
not are serializable (actually they
are - to XAML), they bring a
dependency to WPF (the
System.Windows namespace), and some
other arguments. Also,
DependencyObjects support other
options, like attached properties
and dependency properties. Others
might like to use for example
INotifyPropertyChanged if it
makes sense, and others might say that
all of these patterns don't belong in
other layer than UI.
(If you want to learn more there are
some good WPF data binding
articles in the MSDN library,
including best practices for
perfomance and for user interface)
It's kind of bad that Microsoft has chosen to add some of the goodies to the System.Windows namespace, instead of, for example, to the System.ComponentModel where in my opinion they might have been more useful (by providing all of these important patterns not only to WPF but to the .NET Framework).
Of course this is just the beginning and many of us know that the thing will be evolving to the right direction in the end. (With the risk of going off-topic: Take silverlight 2.0 framework for example. It was a rushed release, with some of the objects in the WPF model missing and some not in their natural place.)
In the end, everything depends on you, your programming style, your architectural decisions and your knowledge of the technology.
If it seems more natural to do it in a way, than by the book, think why you should and why should you not before taking any decision!

Resources