Search code examples
c#xamlxamarin.formslocalizationivalueconverter

When language is set to French, decimal point separator ',' is ignored in binding to a double property


So I have an Entry bound to a double property with Keyboard="Numeric".

  • NO StringFormat is used, and not modifying/forcing culture at app level.

  • Confirmed that in French the decimal point separator character is "," so "." won't be an allowed character:

    CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator equals ','
    

The issue is when I type "12,3", in the property setter the value is equal to 123. And of course at the end it displays 123 in the Entry field instead of "12,3".

xaml

<Entry Keyboard="Numeric" Text="{Binding MyProperty}"/>

C#

private double _MyProp;

public double MyProperty
{
    get { return _MyProp; }
    set { SetProperty(ref _MyProp, value); }
}

How to overcome this issue?


Solution

  • It seems to be a Xamarin.Forms issue Fixed in #5005, as a workaround, use a value converter:

    <ContentPage.Resources>
        <app1:DecimalPointFixConverter x:Key="DecimalPointFixConverter"/>
    </ContentPage.Resources>
    
    <Entry Keyboard="Numeric" Text="{Binding Path=MyProperty, Converter={x:StaticResource DecimalPointFixConverter}}"/>
    

    DecimalPointFixConverter.cs

    public class DecimalPointFixConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return value;
        }
    
        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return (value as string)?.Replace(',', '.') ?? value;
        }
    }
    

    Related question

    Decimal point is being removed in Entry