Behaviors, Xamarin

Learning to use Behaviors in Xamarin Forms

What is a Behavior?

Behaviors let you attach a piece of functionality to an element in a view. This feature can be reusable and give us an easy way to do unit testing.


Which steps do I have to do?

1⃣  Create the Behavior container class

To add a Behavior in a control you must create a class which inherits from the Behavior<T>  class. The T is equivalent to the control type for which the behavior will be applied.


2⃣  Override the  OnAttachedTo and OnDetachingFrom methods

To make possible the Behavior you have to override the following methods:

?  OnAttachedTo: Is activated once the behavior is attached in the control. This method gets a control type as a parameter.

OnDetachingFrom: Is activated when the behavior is removed from the control. This method gets a control type as a parameter.

⚠  Both OnAttachedTo method as OnDetachingFrom method you must add the same control type as parameters that you added in the class created previously. In this case:  Entry control.


3⃣  Lear the XAML Structure

Every type of control, have a Behaviors collection available. In the structure example, I show you, how to create your XAML Behavior structure.


Let’s create an example

In this example, I created a number and text validation to be applied in the Entry controls.

To do it, I created two classes: NumberValidator to validate that the Entry controls just allow numbers and the TextValidator class, to validate that the Entry controls don’t allow numbers. Is important to know, that you must create a class as behavior controls as you need. And finally, I created the XAML adding the Behaviors.

NumberValidator class:


TextValidator class:


XAML:


Spanish post:

https://medium.com/@reyes.leomaris/trabajando-con-behavior-en-xamarin-forms-89c0f8b3f17e

References:

https://docs.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/behaviors/creating

 

Tagged , ,

Leave a Reply

Your email address will not be published. Required fields are marked *