Is it possible to specify a Xamarin Forms Entry Numeric Keyboard without a comma or decimal point separator?

I need to create a form in which the user must enter his age. I would like to use a numeric keypad:

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

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

+13
source share
3 answers

To limit Entryonly to accepting numbers, you can use Behavior or Trigger .

Both of them will respond to the user entering them. Thus, for your use, you can force a trigger or behavior to look for any characters that are not numbers and delete them.

( , SO , , ):

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);
            }
        }


    }
}

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>
+16

, , , , , , , , , XAML.

+1
if (!string.IsNullOrWhiteSpace(args.NewTextValue))
{
    bool isValid = args.NewTextValue.ToCharArray().All(char.IsDigit);

    ((Editor)sender).Text = isValid ? args.NewTextValue : args.OldTextValue;
}

, . , , , , 21h3 @hvaughan3, , 21h .

, (213).

! editor.TextChanged, , , . OnTextChanging. @hvaughan3 . , - , , OnTextChanged Code ,

if (!editor.Text.All(char.IsDigit)) return;
0

Source: https://habr.com/ru/post/1678950/


All Articles