Xamarin Mask Entry Currency 2 个小数位

Xamarin Mask Entry Currency 2 Decimal Places

我正在使用以下代码来屏蔽货币的输入字段。唯一的问题是我想将输入限制为小数点后两位。我怎样才能修改代码来完成这个?

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, Type targetType, object parameter, 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;
            }
        }

    }

效果: