是否可以指定不带逗号或小数点分隔符的Xamarin表单输入数字键盘? [英] Is it possible specify Xamarin Forms Entry Numeric Keyboard without comma or decimal point separator?

查看:262
本文介绍了是否可以指定不带逗号或小数点分隔符的Xamarin表单输入数字键盘?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须创建一个表单,用户必须在其中输入他的年龄.我想使用数字键盘:

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

推荐答案

要限制Entry仅接受数字,您可以使用

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.

类似这样的行为(请注意,我在SO上编写了所有这些内容,并且没有尝试对其进行编译,请让我知道它是否不起作用):

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


    }
}

然后在您的XAML中:

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>

这篇关于是否可以指定不带逗号或小数点分隔符的Xamarin表单输入数字键盘?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆