Xamarin Forms Tips Part 2 : Numeric Entry Recipes

xamarin forms numeric entry
xamarin forms numeric entry

Hi everyone, here is the second part of my Xamarin Tips series. Just as a reminder. The posts I’ll make for this series will have as case study a simple app. It will be about how I used features available in Xamarin Forms to produce unique UI for the app.

The app’s name is : My Expenditures. It is available on Play store and Microsoft store. It provides you a smart way to manage you expenses and income. And very detailed stats about how you spend or make money. You can download and use it. You will also find in the app all the features I talk about here. Let’s not waste time and dive into the numeric entry recipes.

Xamarin Forms Numeric Entry Recipes

What we will be doing here is adding a feature to an entry which will make it take only numbers. And we will also add a feature to precise the range of numbers which should be input in our numeric entry.

Numbers only

The first step will be to make our entry accept only numbers. We will implement this with Behaviors, though it could also be done using triggers. Lets create a class with the name PlainNumericEntryBehavior

  • First, set your entry to use a numeric keyboard. This is essential first before adding additional code.
Keyboard="Numeric"
  • When we attach the behavior, subscribe to the TextChanged Event.
protected override void OnAttachedTo(Entry bindable)
        {
            base.OnAttachedTo(bindable);

            bindable.TextChanged += TextChanged_Handler;
        }
  • In the method to handle this event, if the new text entered is null or empty, we wet the entry’s value to 0. Else, we check if the new value is a number. If it is, we do nothing. If it is not, we make the entry’s text to be = old text.
protected virtual void TextChanged_Handler(object sender, TextChangedEventArgs e)
        {
            if (string.IsNullOrEmpty(e.NewTextValue))
            {
                ((Entry)sender).Text = 0.ToString();
                return;
            }

            double _;
            if (!double.TryParse(e.NewTextValue, out _))
                ((Entry)sender).Text = e.OldTextValue;
        }

Limiting the value of the numbers entered

In case you have an entry in which you want users to enter numbers which are not above a specific value. For example, entering percentage or age. To perform this, we will leverage the first behavior we created above.

  • Add a property to the first behavior. This property will be an Action.
/// <summary>
/// Check the value entered in the entry and convert it
/// </summary>
protected Action<Entry, string> AdditionalCheck;
  •  Create a new behavior which inherits from the previous one.
  •  In the PlainNumericEntryBehavior the method to handle text changes, modify it to be as shown below.
protected virtual void TextChanged_Handler(object sender, TextChangedEventArgs e)
        {
            if (string.IsNullOrEmpty(e.NewTextValue))
            {
                ((Entry)sender).Text = 0.ToString();
                return;
            }

            double _;
            if (!double.TryParse(e.NewTextValue, out _))
                ((Entry)sender).Text = e.OldTextValue;
            else
                AdditionalCheck?.Invoke(((Entry)sender), e.OldTextValue);
        }
  • Add a maximum value property to the new behavior. This value could be set in XAML or directly in the behavior with a default value
  • Define the AdditionalCheck action. This will check if the new value of the entry is greater the desired maximum value, and perform the appropriate action.
AdditionalCheck = (e, ot) =>
            {
                e.Text = Convert.ToInt32(e.Text) > MaximumAmount ? ot : e.Text.ToString();
            };

Here is the complete code for the first behavior :

public class PlainNumericEntryBehavior : Behavior<Entry>
    {
        /// <summary>
        /// Check about value entered in the entry and convert it
        /// </summary>
        protected Action<Entry, string> AdditionalCheck;

        protected override void OnAttachedTo(Entry bindable)
        {
            base.OnAttachedTo(bindable);

            bindable.TextChanged += TextChanged_Handler;
        }

        protected override void OnDetachingFrom(Entry bindable)
        {
            base.OnDetachingFrom(bindable);
        }

        protected virtual void TextChanged_Handler(object sender, TextChangedEventArgs e)
        {
            if (string.IsNullOrEmpty(e.NewTextValue))
            {
                ((Entry)sender).Text = 0.ToString();
                return;
            }

            double _;
            if (!double.TryParse(e.NewTextValue, out _))
                ((Entry)sender).Text = e.OldTextValue;
            else
                AdditionalCheck?.Invoke(((Entry)sender), e.OldTextValue);
        }
    }

The code for the second behavior is shown below.

public class MaximumAmountEntryBehavior : PlainNumericEntryBehavior
    {
        public int MaximumAmount { get; set; } = 100;

        public MaximumAmountEntryBehavior()
        {
            AdditionalCheck = (e, ot) =>
            {
                e.Text = Convert.ToInt32(e.Text) > MaximumAmount ? ot : e.Text.ToString();
            };
        }
        protected override void OnAttachedTo(BindableObject bindable)
        {
            base.OnAttachedTo(bindable);
        }

        protected override void OnDetachingFrom(BindableObject bindable)
        {
            base.OnDetachingFrom(bindable);
        }

        protected override void TextChanged_Handler(object sender, TextChangedEventArgs e)
        {
            base.TextChanged_Handler(sender, e);
        }
    }

Uisng it in your xaml code is easy, you can do it as follows

<Entry.Behaviors>
                        <behaviours:MaximumAmountEntryBehavior MaximumAmount="100" />
                    </Entry.Behaviors>

Conclusion

In case you wanted to restrict user input to numbers only, and to particular amounts precisely, there you have the code for it. As I mentioned above, this is part of the simple app I built. You can download and use it, and you will find the implemented features on it. Play store and Microsoft store. Open Directly on the store app available on your windows 10 device.

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,  Github  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.