Xamarin Forms 1.3: Triggers and Behaviors

With Xamarin Forms lastest 1.3 version, Xamarin added a big improvement to the platform: Support for Triggers and behaviors.

Triggers allow us to conditionally make actions within XAML, whereas behaviors allow to modify and increment the default behavior of any control. With these two tools, you are going to unleash a brand new level of XAML power.


Triggers

A Trigger is an action fired after a certain situation. This situation is defined in XAML with the Trigger declaration. Each trigger could be composed of one or more TriggerActions

There are two type of Triggers: Style Triggers and View Triggers.


Style Triggers

You can define Triggers inside a Style for a View. These Triggers are binded to a property of the View and a value for that property. If the property gets the exact value, the Trigger is launched, executing the Setters placed inside it, as you can see in the next XAML snippet:

Placeholder="Enter your name" TextColor="Maroon" Opacity="0.5">
   

 

In the code above, you can see a text entry (Entry) defined with an inline style. Inside the style the is a Triggers section with one Trigger defined. This Trigger is looking for the IsFocused property. When it value is true, the control is focused, the setters inside the Trigger are executed. In this example, the opacity of the View is stablished to 1.0 (totally opaque) and the text color is changed to Red:

 

This way, you can add interactivity in your styles in an easy way.

View Triggers

View Triggers are slighty different than Style Triggers. In first place, a View Trigger can be driven by a raising event, a data comparision or a multiple data comparision. For example the following code defines an EventTrigger, handling the Clicked event of a button:

 

When the button is clicked, the Action you put inside the EventTrigger is invoked. But, what action? Well, you can create your own actions indeed. The only you need is to create a new public class implementing the TriggerAction base class:

public class ButtonTrigger : TriggerAction<Button>
{
    protected override async void Invoke(Button sender)
    {
       await sender.FadeTo(0, 2000, Easing.CubicIn);
       await sender.FadeTo(1, 2000, Easing.CubicOut);
    }
}

In the TriggerAction class there is a method called Invoke you need to override in your derived class. This method is the one actually invoked when the trigger is launched. In the code above, the class ButtonTrigger overrides the Invoke method and do two FadeTo animations, one FadeOut and one FadeIn.
Now you only need to add the namespace where the ButtonTrigger class is located to your XAML and you are going to be able to add this action to your Trigger:

xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:triggers="clr-namespace:BehaviorsTriggers.Triggers;
                             assembly=BehaviorsTriggers"
             x:Class="BehaviorsTriggers.Views.MainView">

And ther it is! Now you can add the ButtonTrigger action to your Event Trigger:


This is a very powerful tool to create little reusable pieces of code and add interactivity to your XAML without the need to use C#.


Behaviors

After seeing the Triggers, now is time to take a look into the Behaviors. At first sight it could seem like Trigger and behaviors are the same thing. But not, not they are. While Triggers are driven by conditions you set in XAML and their final use is to execute code under some circumstances, Behaviors are meant to extend the View you apply them to far beyond the normal use.


In a Behavior, you implement the base class Behavior. You get the complete object the behavior is attached to and can handle events, change properties or execute code. To make this your behavior can override two methods: OnAttachedTo, executed when the behavior is being attached to the View, and OnDetachingFrom, executed when the behavior is detaching from it’s View. Lets take a look at one example. In the next sample code you are going to see a Behavior aimed to perform navigation from one page to another:

public class NavigationBehavior : Behavior<Button>
{
   private INavigation navService;

public string TargetPage { get; set; }

protected override void OnAttachedTo(Button bindable)
{
base.OnAttachedTo(bindable);
bindable.Clicked += bindable_Clicked;
}

protected override void OnDetachingFrom(Button bindable)
{
base.OnDetachingFrom(bindable);

bindable.Clicked -= bindable_Clicked;
}

private async void bindable_Clicked(object sender, EventArgs e)
{
this.navService = App.Current.MainPage.Navigation;
var targetPageType = Type.GetType(TargetPage);
var targetPageInstance = (Page)Activator.CreateInstance(targetPageType);
await this.navService.PushAsync(targetPageInstance);
}
}

The code above handles the Clicked button event on the OnAttachedTo method and unsubscribe from it on the OnDetachingFrom method. The code also define a TargetPage property, public. You can enter the value of this property in XAML, making the behavior configurable and reusable. When you click the button, the code simply get the current main page navigation service, uses reflection to instantiate the new page and performs a navigation.
Now, the same way you did previously with TriggerActions, you only need to include your behavior namespace in XAML, so you can use it:

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:behaviors="clr-namespace:BehaviorsTriggers.Behaviors;^
             assembly=BehaviorsTriggers"
             x:Class="BehaviorsTriggers.Views.MainView">


Conclussion

As you can see in this little article, using Triggers and Behaviors in your Xamarin.Forms 1.3+ XAML based app is very easy. At the same time you obtain a way of automatizing things in your user interface XAML code to make it more reusable and, more important, more interactive without the need to go to C#.