Use of Behavior in WPF MVVM?
A Behavior is the thing you attach to an element and specifies when the application should respond.
The Action is attached to the behavior and defines what the application should do when the behavior is triggered.
From this article:
At a glance, a behavior looks similar to an action: a self-contained unit of functionality. The main difference is that actions expect to be invoked, and when invoked, they will perform some operation. A behavior does not have the concept of invocation; instead, it acts more as an add-on to an object: optional functionality that can be attached to an object if desired. It may do certain things in response to stimulus from the environment, but there is no guarantee that the user can control what this stimulus is: it is up to the behavior author to determine what can and cannot be customized.
And from this article:
Behaviors let you encapsulate multiple related or dependent activities plus state in a single reusable unit.
I highly recommend reading Introduction to Attached Behaviors in WPF that demonstrates:
- What is attached behavior
- What are it's alternatives
- It's advantages compared to alternative solutions to similar problems
The idea is that you set an attached property on an element so that you can gain access to the element from the class that exposes the attached property. Once that class has access to the element, it can hook events on it and, in response to those events firing, make the element do things that it normally would not do. It is a very convenient alternative to creating and using subclasses, and is very XAML-friendly.
Conclusion from the above article:
Hooking an event on an object and doing something when it fires is certainly not a breakthrough innovation, by any stretch of the imagination. In that sense, attached behaviors are just another way to do the same old thing. However, the importance of this technique is that it has a name, which is probably the most important aspect of any design pattern. In addition, you can create attached behaviors and apply them to any element without having to modify any other part of the system. It is a clean solution to the problem raised by Pascal Binggeli, and many, many other problems. It's a very useful tool to have in your toolbox.