Attach Behaviour Vs Routed Command - wpf

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.

Related

Diffrence between Triggers, Behaviors and Commands in MVVM?

Can anyone please explain difference between Triggers, Behaviors and Commands. I tried to search on this, but could not find anything useful.
And would also like to know in which scenario which one should be preferred and which one is used frequently among them?
Behavior is a way of interactivity without writing code. Behaviors makes interactivity much simpler for the designers. In short, a behavior is a reusable piece that encapsulates some functionality that can be attached to an object to extend its built-in interactivity capabilities.
Commands are used to encapsulate a piece of logic, which various Silverlight controls can bind to and execute in response to an event, such as a button being clicked. You can expose a command from a ViewModel as a property and bind the Command property of a control in the View to it. When the control is clicked, the command will be executed.
In MVVM scenarios, triggers are used to notifying the view of an event from a ViewModel.
For example, perhaps the view needs to navigate to another view once a save operation is
complete. You can implement this behavior by raising an event from the ViewModel that the view can listen for by doing either of the following:
• Wiring up an event handler in the view’s code-behind and writing some code to
respond to the event (Not recommended approach)
• Implementing a trigger in the view that listens for the event and responds accordingly
You can see this, this and this for more explanations.
Also, Pro Business Applications with Silverlight 5 is a very good reference for you.

How do Behaviors and ViewModels relate in MVVM?

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.

Rigid adherence to the MVVM pattern?

I am building a WPF application and using the MVVM for the first time. Overall using MVVM has been very interesting and one of the major benefits is the nice separation between the view and the model classes. It kind of disciplines (at least young developers) to not to mix them together.
We have a scenario where a window needs to be closed on a button click after a confirm message box. Now this can achieved the old-way by handling the button click event and closing the window in the Window class itself. Or we can do it MVVM way by creating a command in ViewModel, call Window to show message box..etc.
I understand what needs to done here, but my question is - is it necessary to use MVVM commands in all cases? Are there exceptions where we should not use commands e.g. simple UI actions? Are we not overusing MVVM here? What exactly will the benefits doing everything the MVVM-way?
Or we can do it MVVM way by creating a command in ViewModel, call Window to show message box..etc.
Let me pick this apart, mainly because IMVHO I see this done wrong all the time - a lot of people try to do too much in the VM. First of all, ask yourself the question:
Is the prompt related to the data or business rules in any way whatsoever?
If it isn't, i.e. it is simply a "are you really sure?" type prompt, then this SHOULD be done purely within the code behind of the view. The only time the viewmodel needs to have any knowledge or take any action is when it actually has something to do with the viewmodel, in which case you should expose a command from the VM, but the actual window closing is still done from the code behind of the view.
The VM should know nothing about the view that it is bound to, that is one of the purposes of the MVVM pattern. It can expose commands, but it shouldn't know that a user has interacted with a specific UI element1, and it shouldn't directly know that the window is about to be closed. It is okay for the VM to prompt (via a dialog service, which you do have, yeah?) that the current data is unsaved, but it doesn't know about the window in general because it doesn't know how its data is presented.
Sometimes you will walk a fine line, and it is easy to over analyze whether something should be done purely from the view, purely from the VM, or as a mixture of both. If you remember the role of the VM, and remember that it is okay to have code behind in the view (provided it is only doing view related stuff and handing VM stuff off to the VM) then 99% of the time you won't have a problem.
1 For example, the VM shouldn't know or care whether the user just clicked a button, hyperlink, or touched a hot spot in an image. The same command can be used to handle any of this.

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.

WPF - Should a user control be supplied with a ViewModel

I'm about to use a user control developed by a different team (in the same company) and for the app we're developing we're attempting to describe all the data binding in XAML.
Now if I use a third party user control should I expect them to supply a basic ViewModel with hooks for my code or should I expect to write code to bind the user control to a ViewModel of my choice?
Cheers
AWC
It depends on the scope of the UserControl. If it is particular to the application and is unlikely to be useful elsewhere then yes, a public ViewModel should probably be supplied.
However, a public ViewModel is likely to be less useful where the control is expected to be re-usable. The control may use a ViewModel internally, but this should be kept private. Then the host application uses the control in a similar way to any other WPF control, and creates it's own view model to tie the control to the application.
In essence, a ViewModel is usually particular to an application - it is tailored specifically to the needs of that application. Whereas general purpose controls expose properties and events that allow them to be used in any application.
Write the controller class yourself. A reusable control should not know which type of data it's working with, unless it's specifically written for it. But then it wouldn't be very reusable :)
The control is supplied as a self contained unit. If it has it's own viewmodel internally which has hooks exposed that is all great, but to you it doesn't matter because you cannot manipulate it directly.
If you really feel the need then you should write your own viewmodel for the supplied control, as this abstracts the UI (the supplied control) from the controller (your code). That is one of the purposes of the pattern - to separate concerns, so you can swap out any part with minimal effect on the remaining parts.
But having said that, not every control is going to need its own viewmodel, instead you would use the supplied control as part of a larger user control, and write a viewmodel for that larger control.

Resources