Xamarin Forms Tips Part 1: Xamarin Forms Entry With Character Max Length And Counter

Hi guys, When building your Xamarin.Forms application there are several tips you should take into consideration to improve user experience. The Xamarin.Forms framework makes it easier to build cross platform applications, but, you can customize its functionalities for your use case. Personalizing your application, and adding additional functionalities not difficult. But for anyone new to Xamarin Forms, accomplishing these improvements may be tricky. Therefor, I decided to start a series of blog posts where I share several tips. These tips will be about adding extra functionalities to what Xamarin Forms already provides to its developers.

So, Here is the first tip. It is simple, and very necessary. Especially when it comes to user experience. We will talk about enabling character maximum length limits in a Xamarin.Forms entry, and displaying a live counter. This counter will display the number of characters which the user has to enter before the max length limit.

Building a Xamarin Forms Entry with Character Max Length and Counter

Accomplishing this requires a behavior, value converter and data binding. The behavior will serve in implementing the max length property on the entry. It does so by listening to each time a character is entered by the user. Then, calculating the length precised by the developer and ignoring every character which the user input after the limit reached. Here is the behavior :

private void Bindable_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (string.IsNullOrEmpty(e.NewTextValue))
                return;

            if (e.NewTextValue.Length >= TextLenght)
                ((Entry)sender).Text = e.OldTextValue;
        }

In the above code, we use the behavior to listen to text changes on the entry. And ignore any change made if it’s the length is greater than the Max Length.

Here is the full code for the behavior.

public class LimitedLengthEntryBehavior : Behavior<Entry>
    {
        public int TextLenght { get; set; } = 30;

        protected override void OnAttachedTo(Entry bindable)
        {
            base.OnAttachedTo(bindable);
            bindable.TextChanged += Bindable_TextChanged;
        }

        private void Bindable_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (string.IsNullOrEmpty(e.NewTextValue))
                return;

            if (e.NewTextValue.Length >= TextLenght)
                ((Entry)sender).Text = e.OldTextValue;
        }

        protected override void OnDetachingFrom(Entry bindable)
        {
            bindable.TextChanged -= Bindable_TextChanged;
        }
    }

Now, to display the number of characters which the user has to type before the limit, we will use a value converter. Its role will be to get the number of characters entered and use it to calculate the number of characters left. This value converter will have the max length property (_wordCount )set with the same value as that of the behavior – 1. This max length will be decremented each time a character is entered and vice versa. Here is the code for the value converter.

public class TextLengthValidationValueConverter : IValueConverter
   {
       int _wordCount = 29;

       public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
       {
           return value == null ? value : (_wordCount) - System.Convert.ToInt32(value); 
       }

       public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
       {
           throw new NotImplementedException();
       }
   }

Applying these to our XAML code is what is left. The behavior is applied normally as shown below.

<Entry.Behaviors>.
     <behaviours:LimitedLengthEntryBehavior />
</Entry.Behaviors>

Now, the converter will be used on a label beside the entry (You may use it on another control). Taking into consideration that the label is stacked horizontally with the entry (I just decided to stack it, this is not a requirement for it to work). This label is bound to the length of characters which the entry has, and uses the converter to display the number  characters remaining. Here it is:

<Label
    Style="{StaticResource LegendLabelStyle}"
    Text="{Binding Text.Length, Source={x:Reference TitleEntry}, Mode=TwoWay, Converter={x:StaticResource TextLengthValidationConverter}}"
    VerticalOptions="End" />

Conclusion

Using the above code, you should be able to implement a Xamarin Forms entry with character max length and counter. What I explained in this article is not limited only to a label beside an entry. You can create a custom entry using custom renderers. And add a property to the entry which automatically does the job of the label I used above. Bellow, you can see the demo which I implemented. It is a screen shot from a simple application I will soon distribute to Microsoft and Play stores.  Here is the link to the application on Play store.   If you like the application and find it useful, please don’t forget to rate it.

Xamarin Forms entry with character max length and counter demo
Xamarin Forms entry with character max length and counter demo

You may also like this post about using LiteDB as an alternative to SQLite. To get code samples about Xamarin Forms posts made on this blog, check this.

If you liked this post, or it was useful to you, please 👍 like it, share it on twitter, facebook or other social media… in case you want to get updated on any new useful post, follow me on twitter  and like my page on facebook. And every other social media by clicking on the  buttons at the end of this post.

Follow me on social media and stay updated

Follow me on social media and stay updated

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.