How to create Xamarin.Forms Behaviors?
Harshal Suthar
Posted on May 10, 2022
Behaviors allow us to add functionalities to the UI (User Interface) controls without sub-classing them. Behaviors are written in code behind file and added to the controls. The controls are in XAML or code.
In this blog, we will discuss Xamarin.Forms Behaviors. Xamarin.Forms behaviors are created by deriving Behavior or Behavior class, where T is a type of control on which behavior will apply.
Follow this process to create Xamarin.Forms behaviors: First of all, create a class and inherit Behavior or Behavior class. After inheriting the Behavior class override the OnAttachedTo and OnDetachingFrom methods. OnAttachedTo method is used to perform any required setup and the OnDetachingFrom method is used to perform any required cleanup. Now, we can implement the functionalities of behaviors.
This code shows a structure of behavior for Entry control’s
public class EntryControlBehavior : Behavior<entry>
{
protected override void OnAttachedTo (Entry entry)
{
base.OnAttachedTo (entry);
// Perform setup
}
protected override void OnDetachingFrom (Entry entry)
{
base.OnDetachingFrom (entry);
// Perform clean up
}
// Behavior implementation
}
</entry>
Let’s create a simple application using behaviors for Xamarin.Forms.
Create New project >> Select Cross-Platform >> Select Mobile App (Xamarin.Forms).
Give an appropriate name to the project and then click OK
Now choose Template and Platform, and then click on the OK button.
In this step, we will see how to create behavior. Create a new folder for behavior so we can identify behaviors easily. Right-click on that folder >> Click Add >> Click on Class.
Read More: Oauth Login Authentication With Identity Provider In Xamarin.forms
Select Visual C# Items >> Class >> Give Name to the class >> Click on Add
After creating a class inherit that class with Behavior to create behaviors and override OnAttachedTo and OnDetachingFrom methods.
Here, we will create various entrssy controls and picker control and applies behaviors to these controls. We will apply behavior for Email, Date of Birth, Mobile Number, and Password.
Emailvalidationbehavior.cs
using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using Xamarin.Forms;
namespace XamarinFormsBehaviors.Behaviors
{
public class Emailvalidationbehavior:Behavior<entry>
{
const string emailre= @"^(?("")("".+?(?<!--\\)""@)|(([0-9a-z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-z])@))" +
@"(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-z][-\w]*[0-9a-z]*\.)+[a-z0-9][\-a-z0-9]{0,22}[a-z0-9]))$";
protected override void OnAttachedTo(Entry bindable)
{
bindable.TextChanged += Textchanged;
base.OnAttachedTo(bindable);
}
private void Textchanged(object sender, TextChangedEventArgs e)
{
bool IsValid = false;
IsValid= (Regex.IsMatch(e.NewTextValue, emailre, RegexOptions.IgnoreCase, TimeSpan.FromMilliseconds(250)));
((Entry)sender).TextColor = IsValid ? Color.Default : Color.Red;
}
protected override void OnDetachingFrom(Entry bindable)
{
bindable.TextChanged -= Textchanged;
base.OnDetachingFrom(bindable);
}
}
}
</entry--></entry>
In this class, we will create a behavior for the Email validation. It matches the format of email with given regular expression, if a user enters an invalid format of email, then it will show entered text in Red color.
DatevalidationBehavior.cs
This class will create a behavior for Date of Birth validation. We will use Date Picker control and restrict the maximum date to be 100 years from the current date and the minimum date to be one. If the user enters 100 years ago date or upcoming dates from today it will set the background color of Picker to Red.
using System;
using Xamarin.Forms;
namespace XamarinFormsBehaviors.Behaviors
{
class DatevalidationBehavior:Behavior<datepicker>
{
protected override void OnAttachedTo(DatePicker datePicker)
{
datePicker.DateSelected+=DatePickerdateSelected;
base.OnAttachedTo(datePicker);
}
private void DatePickerdateSelected(object sender, DateChangedEventArgs e)
{
DateTime dateTime = e.NewDate;
int year = DateTime.Now.Year;
int selectedyear = dateTime.Year;
int res = year - selectedyear;
bool IsValid = false;
if(res<=100 && res > 0)
{
IsValid = true;
}
((DatePicker)sender).BackgroundColor = IsValid ? Color.Default : Color.Red;
}
protected override void OnDetachingFrom(DatePicker datePicker)
{
datePicker.DateSelected -= DatePickerdateSelected;
base.OnDetachingFrom(datePicker);
}
}
}
</datepicker>
MobilenovalidationBehavior.cs
This class will create a behavior for mobile numbers. The user must have to add integers otherwise it will show text in Red color.
Planning to Hire Xamarin App Development Company ? Your Search ends here.
using Xamarin.Forms;
namespace XamarinFormsBehaviors.Behaviors
{
public class MobilenovalidationBehavior:Behavior<entry>
{
protected override void OnAttachedTo(Entry mnoentry)
{
mnoentry.TextChanged += MobilenoChanged;
base.OnAttachedTo(mnoentry);
}
private void MobilenoChanged(object sender, TextChangedEventArgs e)
{
int num;
bool Isvalid = int.TryParse(e.NewTextValue, out num);
((Entry)sender).TextColor = Isvalid ? Color.Default : Color.Red;
}
protected override void OnDetachingFrom(Entry mnoentry)
{
mnoentry.TextChanged -= MobilenoChanged;
base.OnDetachingFrom(mnoentry);
}
}
}
</entry>
PasswordvalidationBehavior.cs
This class creates behavior for password validation, the length of the password must be between 8 to 15 and it must contain numeric and alphabetic values otherwise the color of entered text will be changed to Red.
using System;
using System.Text.RegularExpressions;
using Xamarin.Forms;
namespace XamarinFormsBehaviors.Behaviors
{
public class PasswordvalidationBehavior:Behavior<entry>
{
const string passwordreg = @"^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).{8,15}$";
protected override void OnAttachedTo(Entry pwentry)
{
pwentry.TextChanged += Textchanged;
base.OnAttachedTo(pwentry);
}
private void Textchanged(object sender, TextChangedEventArgs e)
{
bool isvalid = false;
isvalid= (Regex.IsMatch(e.NewTextValue, passwordreg, RegexOptions.IgnoreCase, TimeSpan.FromMilliseconds(250)));
((Entry)sender).TextColor = isvalid ? Color.Default : Color.Red;
}
protected override void OnDetachingFrom(Entry pwentry)
{
pwentry.TextChanged -= Textchanged;
base.OnDetachingFrom(pwentry);
}
}
}
</entry>
Now, add behaviors to the XAML file, add a namespace to the XAML file and add behaviors to control as added in the below code.
<!--?xml version="1.0" encoding="utf-8" ?-->
<contentpage x:class="XamarinFormsBehaviors.MainPage" xmlns="http://xamarin.com/schemas/2014/forms" xmlns:b="clr-namespace:XamarinFormsBehaviors.Behaviors" xmlns:local="clr-namespace:XamarinFormsBehaviors" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml">
<contentpage.resources>
<resourcedictionary>
<color x:key="LightGreenColor">#2FA999</color>
<color x:key="BorderColor">#D8D8D8</color><style targettype="Label" type="text/css" x:key="LableStyle"><Setter Property="TextColor" Value="#666666" />
<Setter Property="FontSize" Value="Large" /></style><style targettype="Frame" type="text/css" x:key="FrameStyle"><Setter Property="HasShadow" Value="False" />
<Setter Property="Padding" Value="0" />
<Setter Property="CornerRadius" Value="5" />
<Setter Property="BorderColor" Value="{StaticResource BorderColor}" /></style><style targettype="Entry" type="text/css" x:key="EntryStyle"><Setter Property="HeightRequest" Value="50"></Setter>
<Setter Property="Margin" Value="5,0,0,0"></Setter>
<Setter Property="PlaceholderColor" Value="LightGray"></Setter></style>
</resourcedictionary>
</contentpage.resources>
<stacklayout>
<label fontsize="Medium" horizontaloptions="Center" text="Registration" textcolor="Black" verticaloptions="Center">
<stacklayout margin="5" padding="5">
<label style="{StaticResource LableStyle}" text="Name">
<entry placeholder="Enter Your Name Here.." style="{StaticResource EntryStyle}">
<label style="{StaticResource LableStyle}" text="Email">
<entry placeholder="Enter Your Email Here.." style="{StaticResource EntryStyle}">
<entry.behaviors>
<b:emailvalidationbehavior>
</b:emailvalidationbehavior></entry.behaviors>
</entry>
<label style="{StaticResource LableStyle}" text="Mobile Number">
<entry placeholder="Enter Your Mobile Number.." style="{StaticResource EntryStyle}">
<entry.behaviors>
<b:mobilenovalidationbehavior>
</b:mobilenovalidationbehavior></entry.behaviors>
</entry>
<label style="{StaticResource LableStyle}" text="Select Date of Birth">
<datepicker>
<datepicker.behaviors>
<b:datevalidationbehavior>
</b:datevalidationbehavior></datepicker.behaviors>
</datepicker>
<label style="{StaticResource LableStyle}" text="Password">
<entry ispassword="True" placeholder="Enter Passsword Here..." style="{StaticResource EntryStyle}" x:name="Password">
<entry.behaviors>
<b:passwordvalidationbehavior>
</b:passwordvalidationbehavior></entry.behaviors>
</entry><button backgroundcolor="{StaticResource LightGreenColor}" borderradius="6" margin="100,20" text="Sign Up" textcolor="White" widthrequest="100"></button></label></label></label></label></entry></label></stacklayout></label></stacklayout></contentpage>
Conclusion
Behaviors are used to add more functionalities to our UI. Behaviors are written in code behind file and added to XAML file. In this blog we have seen how to implement behaviors in Xamarin.Forms and create applications with Xamarin.Forms behaviors. We have created behaviors for entry and picker control for that we have built class and inherit behavior to that class and then add these behaviors to our XAML file.
Posted on May 10, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.