Introduction to Behaviors

PDF for offline use
Related APIs:

Let us know how you feel about this

Translation Quality


0/250

last updated: 2016-04

Behaviors let you add functionality to user interface controls without having to subclass them. Instead, the functionality is implemented in a behavior class and attached to the control as if it was part of the control itself. This article provides an introduction to behaviors.

Behaviors enable you to implement code that you would normally have to write as code-behind, because it directly interacts with the API of the control in such a way that it can be concisely attached to the control and packaged for reuse across more than one application. They can be used to provide a full range of functionality to controls, such as:

  • Adding an email validator to an Entry.
  • Creating a rating control using a tap gesture recognizer.
  • Controlling an animation.
  • Adding an effect to a control.

Behaviors also enable more advanced scenarios. In the context of commanding, behaviors are a useful approach for connecting a control to a command. In addition, they can be used to associate commands with controls that were not designed to interact with commands. For example, they can be used to invoke a command in response to an event firing.

Xamarin.Forms supports two different styles of behaviors:

  • Xamarin.Forms behaviors – classes that derive from the Behavior or Behavior<T> class, where T is the type of the control to which the behavior should apply. For more information about Xamarin.Forms behaviors, see Xamarin.Forms Behaviors and Reusable Behaviors.
  • Attached behaviorsstatic classes with one or more attached properties. For more information about attached behaviors, see Attached Behaviors.

This guide focuses on Xamarin.Forms behaviors because they are the preferred approach to behavior construction.

Xamarin Workbook

If it's not already installed, install the Xamarin Workbooks app first. The workbook file should download automatically, but if it doesn't, just click to start the workbook download manually.