是否可以指定没有逗号或小数点分隔符的 Xamarin Forms Entry Numeric Keyboard? [英] Is it possible specify Xamarin Forms Entry Numeric Keyboard without comma or decimal point separator?

查看:13
本文介绍了是否可以指定没有逗号或小数点分隔符的 Xamarin Forms Entry Numeric Keyboard?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 Forms Entry Numeric Keyboard?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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