Xamarin.Forms Numeric Entry comma and Dot not working

4.1k views Asked by At

I have an entry field in Xamarin.Forms.

On Android, I can't enter either a comma or a dot to make decimals. The entry just accepts integral numbers. What do I have to change to be able to enter decimals?

Xaml:

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

Content page cs:

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

                OnPropertyChanged(nameof(Price1));
            }
        }
3

There are 3 answers

0
ColeX On BEST ANSWER

The quickest way is to create a string property with binding , and convert to decimal when using it .

ViewModel

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

            OnPropertyChanged(nameof(Price1));
        }
    }

Usage

 decimal f = Convert.ToDecimal(Price1);
1
ChrisBD On

In my experience Xamarin is a pain with decimal display. You end up entering either side of the decimal point and its behaviour is never consistent.

I find it far easier to have the ViewModel supply a non-decimal integer value and use a value convertor to display it as a decimal.

e.g.

<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;
        }
    }
0
Joshua Beckers On

As @Cole Xia - MSFT pointed out the problem with the code in the question is that the input is immediately converted from String into Decimal. This leads to having the decimal point/comma stripped away during the conversion. Therefore you have to keep the content of entry as String for the entire time and convert it to a numeric type at the time of usage.