【问题标题】:Xamarin.Forms Numeric Entry comma and Dot not workingXamarin.Forms 数字输入逗号和点不起作用
【发布时间】:2020-08-10 17:12:58
【问题描述】:

我在 Xamarin.Forms 中有一个输入字段。

在 Android 上,我无法输入逗号或点来生成小数。该条目只接受整数。我必须更改什么才能输入小数?

Xaml:

<Entry Keyboard="Numeric" Text="{Binding Price1}" Placeholder="Price"/>

内容页cs:

        private decimal price1;
        public string Price1
        {
            get { return (price1).ToString(); }
            set
            {
                price1 = Convert.ToDecimal((String.IsNullOrEmpty(value)) ? null : value);

                OnPropertyChanged(nameof(Price1));
            }
        }

【问题讨论】:

    标签: c# xamarin xamarin.forms xamarin.android xamarin.forms.entry


    【解决方案1】:

    最快的方法是创建一个带有绑定的字符串属性,并在使用时转换为十进制。

    视图模型

        private string price1;
        public string Price1
        {
            get { return price1; }
            set
            {
                price1 = value;
    
                OnPropertyChanged(nameof(Price1));
            }
        }
    

    用法

     decimal f = Convert.ToDecimal(Price1);
    

    【讨论】:

      【解决方案2】:

      根据我的经验,Xamarin 对小数显示感到很痛苦。您最终会输入小数点的任一侧,并且其行为永远不会一致。

      我发现让 ViewModel 提供一个非十进制整数值并使用值转换器将其显示为十进制要容易得多。

      例如

      <Label x:Name="CpvValueText" Text="{Binding ScaledValue, Mode=OneWay, Converter={x:StaticResource DecimalConverter}}" />
      

      ...

         /// <summary>
          /// This helper class converts integer values to decimal values and back for ease of display on Views
          /// </summary>
          public class DecimalConverter : IValueConverter
          {
              /// <inheritdoc />
              public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
              {
                  if (null == value)
                  {
                      return 0;
                  }
      
                  var dec = ToDecimal(value);
                  return dec.ToString(CultureInfo.InvariantCulture);
              }
      
              /// <inheritdoc />
              public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
              {
                  var strValue = value as string;
                  if (string.IsNullOrEmpty(strValue))
                  {
                      strValue = "0";
                  }
      
                  return decimal.TryParse(strValue, out var result) ? result : 0;
              }
          }
      

      【讨论】:

      • 如何在您的示例中输入数字?显示数字但输入数字没有问题。
      【解决方案3】:

      正如@Cole Xia - MSFT 指出问题中代码的问题在于 输入立即从字符串转换为十进制。这会导致在转换过程中去除小数点/逗号。因此,您必须始终将条目的内容保持为String,并在使用时将其转换为数字类型。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-11-06
        • 2018-11-13
        • 2015-09-20
        • 2017-08-14
        • 1970-01-01
        • 2022-09-22
        • 2014-02-21
        • 1970-01-01
        相关资源
        最近更新 更多