Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

xamarin.forms - Is it possible specify Xamarin Forms Entry Numeric Keyboard without comma or decimal point separator?

I have to create a form in which the user must input his age. I would like to use a numeric keyboard:

    <Entry
        x:Name="AgeEntry"
        VerticalOptions="FillAndExpand"
        HorizontalOptions="FillAndExpand"
        Keyboard="Numeric"
    />

but it shows even the decimal point character, I'd like to show only numbers...

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

To restrict the Entry to only accept numbers you could use a Behavior or a Trigger.

Both of those will react to a user typing into them. So for your use, you could have the trigger or behavior look for any characters that are not numbers and remove them.

Something like this for a behavior (note that I wrote all this on SO and did not try compiling it, let me know if it does not work):

using System.Linq;
using Xamarin.Forms;

namespace MyApp {

    public class NumericValidationBehavior : Behavior<Entry> {

        protected override void OnAttachedTo(Entry entry) {
            entry.TextChanged += OnEntryTextChanged;
            base.OnAttachedTo(entry);
        }

        protected override void OnDetachingFrom(Entry entry) {
            entry.TextChanged -= OnEntryTextChanged;
            base.OnDetachingFrom(entry);
        }

        private static void OnEntryTextChanged(object sender, TextChangedEventArgs args) 
        {

            if(!string.IsNullOrWhiteSpace(args.NewTextValue)) 
            { 
                 bool isValid = args.NewTextValue.ToCharArray().All(x=>char.IsDigit(x)); //Make sure all characters are numbers

                ((Entry)sender).Text = isValid ? args.NewTextValue : args.NewTextValue.Remove(args.NewTextValue.Length - 1);
            }
        }


    }
}

Then in your XAML:

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         xmlns:local="clr-namespace:MyApp;assembly=MyApp"> <!-- Add the local namespace so it can be used below, change MyApp to your actual namespace -->

  <Entry x:Name="AgeEntry"
         VerticalOptions="FillAndExpand"
         HorizontalOptions="FillAndExpand"
         Keyboard="Numeric">
    <Entry.Behaviors>
      <local:NumericValidationBehavior />
    </Entry.Behaviors>
  </Entry>

</ContentPage>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...