0

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

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

xml:

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

3 回答 3

0

以我的经验,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;
        }
    }
于 2020-04-27T07:56:53.673 回答
0

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

视图模型

    private string price1;
    public string Price1
    {
        get { return price1; }
        set
        {
            price1 = value;

            OnPropertyChanged(nameof(Price1));
        }
    }

用法

 decimal f = Convert.ToDecimal(Price1);
于 2020-04-27T08:43:28.793 回答
0

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

于 2020-04-27T08:50:57.913 回答