Xamarin.Forms Creating a custom Entry control with a MaxLength property


The Xamarin Forms Entry control does not have a MaxLength property. To achieve this you can extend Entry as below, by adding a Bindable MaxLength property. Then you just need to subscribe to the TextChanged event on Entry and validate the length of the Text when this is called:

class CustomEntry : Entry
    public CustomEntry()
        base.TextChanged += Validate;

    public static readonly BindableProperty MaxLengthProperty = BindableProperty.Create(nameof(MaxLength), typeof(int), typeof(CustomEntry), 0);

    public int MaxLength
        get { return (int)GetValue(MaxLengthProperty); }
        set { SetValue(MaxLengthProperty, value); }
    public void Validate(object sender, TextChangedEventArgs args)
        var e = sender as Entry;
        var val = e?.Text;

        if (string.IsNullOrEmpty(val))

        if (MaxLength > 0 && val.Length > MaxLength)
            val = val.Remove(val.Length - 1);

        e.Text = val;

Usage in XAML:

   <ContentView xmlns="http://xamarin.com/schemas/2014/forms" 
    <customControls:CustomEntry MaxLength="10" />