xamlxamarin.formscustom-formatting

Space as thousands separator for labels


I have a label and im using binding and a FormatString as such:

<Label Text="{Binding buying_price , StringFormat='{0} EUR'}">

The label's text is bound to a double in my ViewModel, what im getting on the label is something like this: 10000 EUR, what i want to get is 10 000 EUR, and 12 501 005 EUR for example (without the trailing .00). I tried StringFormat='{0:C2} EUR' and StringFormat='{0:N} EUR' and StringFormat='{0:n} EUR' but non of them gave me a good result.


Solution

  • I did not make it work in xaml, while when I use a convert and use string format in code behind, it works as excepted:

    <ContentPage.Resources>
        <ResourceDictionary>
            <local:thousandsSeparatorConverter x:Key="thousandsSeparator"/>
        </ResourceDictionary>
    </ContentPage.Resources>
    
    <StackLayout>
        <!-- Place new controls here -->
        <Label Text="{Binding date, Converter={StaticResource thousandsSeparator}}"  HorizontalOptions="CenterAndExpand" VerticalOptions="CenterAndExpand"/>
        
    </StackLayout>
    

    And the local:thousandsSeparatorConverter :

    public class thousandsSeparatorConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            string s = value as string;
    
    
            double number = double.Parse(s);
    
            // Gets a NumberFormatInfo associated with the en-US culture.
            NumberFormatInfo nfi = new CultureInfo("en-US", false).NumberFormat;
    
            // Displays the same value with a blank as the separator.
            nfi.NumberGroupSeparator = " ";
            Console.WriteLine(number.ToString("N0", nfi));
    
            string convertedNumber = number.ToString("N0", nfi);
    
            return convertedNumber;
        }
    
        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return value;
        }
    
    }