Xamarin掩码输入货币2个小数位

问题描述

我正在使用以下代码掩盖货币输入字段。唯一的问题是我想将输入限制为2个小数位。如何修改代码以实现此目的?

public class CurrencyConverter : IValueConverter
{
    public object Convert(object value,Type targettype,object parameter,CultureInfo culture)
    {
        return Decimal.Parse(value.ToString()).ToString("C");
    }

    public object ConvertBack(object value,CultureInfo culture)
    {
        string valueFromString = Regex.Replace(value.ToString(),@"\D","");

        if (valueFromString.Length <= 0)
            return 0m;

        long valueLong;
        if (!long.TryParse(valueFromString,out valueLong))
            return 0m;

        if (valueLong <= 0)
            return 0m;

        return valueLong / 100m;
    }
}

解决方法

如果要限制两位小数,可以将条件添加到条目textchanged事件中。

喜欢:

<Entry x:Name="entry" Keyboard="Numeric"  HorizontalOptions="StartAndExpand" WidthRequest="600" TextChanged="Entry_TextChanged"></Entry>

在后面的代码中:

private void Entry_TextChanged(object sender,TextChangedEventArgs e)
    {
      
        if (e.NewTextValue.Contains("."))
        {
            if (e.NewTextValue.Length - 1 - e.NewTextValue.IndexOf(".") > 2)
            {
              var  s = e.NewTextValue.Substring(0,e.NewTextValue.IndexOf(".") + 2 + 1);
                entry.Text =s;
                entry.SelectionLength = s.Length;
            }
        }

    }

效果:

enter image description here

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...