Use of Behavior in WPF MVVM? - wpf

I am new to WPF MVVM .. Anybody clear the usage of the Behaviors in MVVM application in WPF?. Why we should go for Behavior even we have Method action 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.

In MVVM you may need to call methods from the View if your ViewModel exposes methods, not commands. Behaviors allow for this.
You state "we have Method action in WPF MVVM", but as far as I know "method action" is not part of WPF. If you are using a helper MVVM library, it may provide "method action" that could encapsulate methods in commands. In such a case, behaviors are not required for the MVVM pattern using methods.
Note, though, that behaviors have other uses outside of MVVM.

Related

when to use a behavior and when to use a trigger&action in wpf?

I researcher mvvm in wpf.
I know how to use a behavior and how to use a trigger&action, but I don't understand when!
I look for info but I find only theoretical metirial, not practical.
thank you!
The WPF Behavior is a way to encapsulate a part of complicated UI logic into reusable coded component.
http://www.wpftutorial.net/Behaviors.html.
https://msdn.microsoft.com/en-us/library/ff726531(v=expression.40).aspx
It is a bad practice when a viewmodel and a behavior are strongly-coupled with each other, this can cause a reusing problem. I think that this is a main different between these two concepts (Triggers&Action/Behavior). Trigger&Action is local solution to convert the Event to command and move the event handling logic toward the viewmodel (you can see here that wthe trigger&action approach is strongly coupled with the viewmodel).
Summary:
If you want to create piece of complicated logic, that will be a reusable concept used in more then one control, and moreovere this component won't have any access to the view model - use the behavior approach.
If you want just to convert some event to command and to move the event handling logis to viewmodel - use the trigger&action approach.
regards,
There are a lot of objects in WPF which doesn't have any triggers of actions fit to them.
for example: Rectangles.
If you want, for example, to make it possible for clicking on a rectangle and do something, use behavior.
For more information you can look here and also here.

Design pattern for Viewmodel change triggering another viewmodel change?

In my WPF application, I have several models and viewmodels. Consider an example:
The SurfaceCondition property of my RoadViewmodel changes. I want this to (asynchronously) trigger a change of the Wheel property of my CarViewmodel.
I can think of several solutions, but I sense this particular problem has a well-recognized solution. Using messages? Putting a reference in the RoadViewmodel to the CarViewmodel and trigger an update through the property? Merging the viewmodels? WPF gurus out there, please enlighten me!
Definitely not the two last solutions you propose as they violate Seperation Of Concerns (RoadViewModel knowing about CarViewModel) / DRY principles (RoadViewModel having to update CarViewModel or merging two classes).
Messages on the other hand seems like a fine, decoupled solution here. There are a couple of implementations available, for example Prism has en EventAggregator class, MVVM Toolkit has MessageBus etc. Or search for terms like 'MVVM event bus'. Now whatever you choose, know that it is always good to not use those classes directly but instead pass an interface. For example with Prism, you'd program your viewmodels to use the IEventAggregator interface only. In the actual application you pass them an instance of the actual EventAggregator, whereas during unit tests you pass the a mock.

Why is TriggerAction internal?

Is there ans good reason why the TriggerEvent class usd in EventTriggers is implemented internal? I can find 3 implementations of this abstract base Claas. One to play a sound and two different actions regarding storyboards. What if I want to have a "SendEmail" action? Is more a hypothetical question. I don't have n actual application for it. I just noticed it and was wondering why it is implemented this way. To me it would be logical to derive my own action and just use it in the event trigger (an interface would be even better). Am I missing a point here?
Regards!
I doubt that you can do anything with those classes, use Interactivity from the Blend SDK instead, which provides classes (TriggerAction<T> for example) that can be sub-classed.
Edit: Somehow this is only found in the Silverlight documentation of the class:
TriggerAction exists in Silverlight for WPF compatibility. TriggerAction is not intended to be derived from as a base for other trigger implementations; the entire Triggers syntax is a discouraged technique in Silverlight 4. For more information, see Remarks in EventTrigger, or Customizing the Appearance of an Existing Control by Using a ControlTemplate.
Still no reason though.

Interactivity.Behavior<T> vs attached properties

I'm trying to find some differences between these approaches. Is there any situation where behaviors are used and the same functionality could not be done with attached properties?
No. Behaviors are basically just a much nicer abstraction on top of attached properties.
By using Behavior<T>, you gain access to the AssociatedObject directly, as well as the ability to attach and detach the behavior, easily, at runtime.
You could do this with attached properties, but it would require adding a lot of extra plumbing.
I tend to use Behaviors to add functionality which makes visible changes. Whereas I use attached properties to add additional information to an object which is subsequently used by other objects.
E.g. Grid.Row makes a good attached property, as it's used by the Grid and not the target. On the other hand, AutoCorrect would make a good behaviour, as this will make visible changes on the object.
Behaviors are based on attached properties. That means if you can't find specific behavior - you write your own, either based on behaviors framework provided by Blend or by creating your own AP...
I always thought that behaviors are great evidence of attached properties power. Just incredible what you can get with them.
This is not the answer. But the best explanation I can find on this topic
https://web.archive.org/web/20180208143035/http://briannoyesblog.azurewebsites.net/2012/12/20/attached-behaviors-vs-attached-properties-vs-blend-behaviors/
Brian Noyes in his articles clearly describes the differences between each of the concepts.

WPF control inheritance

I've read in a blog the following sentence:
The first rule of WPF:
Avoid control inheritance.
I've seen similar things in other places as well.
However, I fail to understand the logic.
Moreover, I see suggestions here in StackOverflow that involves inheriting WPF controls (see the replies to my previous question for example).
I would like to understand why (and if) control inheritance should be avoided.
WPF controls are "lookless". In other words, their look is separated from their behavior. More often than not, you actually want to customize the look - not the behavior. Unlike the world of Winforms, this does not require you to inherit a new control and override rendering logic. Instead, you set some properties on the control, resorting to overriding the template itself if you can't get the look you want from other properties.
Note that "avoid" means just that. Avoid inheritance if you can. In cases where you need to modify behavior, inheritance may well be the best option.
The blog from the link also states in the end that:
"With Styles, Templates, Decorators and attached properties and behaviors you can accomplish most of the things that you used to have to roll a new control for."
That is true. However, were it always true, the wpftoolkit team wouldn't have made their DataGrid as a subclass of MultiSelector.
Judge each case separately, I would say. Also check this answer.

Resources