Xamarin Forms Create Custom Entry Control

The Xamarin forms entry controls enables us to enter text value on a form. In this post we will see how we can create a Custom renderer for xamarin entry control to customized the entry view. In the default entry control of Xamarin forms there is no option to set border values. We will create a custom renderer in our Android and iOS Xamarin forms projects to assist us to achieve this functionality. Let’s begin.

DOWNLOAD SOURCE CODE
We need to first create a custom entry class. This class by subclassing the Entry control. Create a new class in your PCL project with name BorderedEntry.cs, and edit it as below:

BorderedEntry.cs:

using Xamarin.Forms;

namespace AppDemos
{
public class BorderedEntry : Entry
{

}
}

Now in your Android project, create a class file named CustomBorderedEntry.cs. This file while be our EntryRendered for our custom control on Android platform.

CustomBorderedEntry.cs

using Xamarin.Forms.Platform.Android;
using Xamarin.Forms;
using Android.Content;
using Android.Graphics.Drawables;
using Android.Content.Res;
using AppDemos.Droid;
using AppDemos;

[assembly: ExportRenderer(typeof(BorderedEntry), typeof(CustomBorderedEntry))]
namespace AppDemos.Droid
{
public class CustomBorderedEntry : EntryRenderer
{
public CustomBorderedEntry(Context context) : base(context)
{
}

protected override void OnElementChanged(ElementChangedEventArgs<Entry> e)
{
base.OnElementChanged(e);

if (Control != null)
{
Control.SetBackgroundColor(global::Android.Graphics.Color.Transparent);
Control.Bottom = 5;

int[][] states = new int[][] {
new int[] { -Android.Resource.Attribute.StateFocused}, // enabled
new int[] {Android.Resource.Attribute.StateFocused} // disabled
};

int[] colors = new int[] { Color.Black.ToAndroid(), Color.FromHex("#FF4081").ToAndroid() };

ColorStateList myList = new ColorStateList(states, colors);

GradientDrawable gradientDrawable = new GradientDrawable();
gradientDrawable.SetCornerRadius(5);
Control.Background = gradientDrawable;
gradientDrawable.SetStroke(2, myList);
}
}
}
}

In your iOS project, create a class file named CustomBorderedEntry.cs, this file while be our EntryRendered for our custom control on iOS devices,

CustomBorderedEntry.cs

using AppDemos;
using AppDemos.iOS;
using UIKit;
using Xamarin.Forms;
using Xamarin.Forms.Platform.iOS;

[assembly: ExportRenderer(typeof(BorderedEntry), typeof(CustomBorderedEntry))]
namespace AppDemos.iOS
{
public class CustomBorderedEntry : EntryRenderer
{
protected override void OnElementChanged(ElementChangedEventArgs<Entry> e)
{
base.OnElementChanged(e);

if (Control != null)
{
Control.BackgroundColor = UIColor.FromCGColor(Color.Transparent.ToCGColor());
Control.BorderStyle = UITextBorderStyle.Bezel;
Control.Layer.CornerRadius = 5;
//Control.Layer.BorderColor = Color.Black.ToCGColor();
}
}
}
}

Final Result:
Now run application

Xamarin Form Custom Entry

DOWNLOAD SOURCE CODE