Search code examples
xmlxamlstring-formattingtextblock

XAML TextBlock XML: StringFormat to display number


My XML data is:

<Num>12.6</Num>

I bind this to a XAML TextBlock and want to display the value as a rounded number without decimal point. So this value should be displayed as 13. Similarly, 12.2 should be displayed as 12, etc.

I need code in the StringFormat below (at the ...) to do what I want:

<TextBlock Text= "{Binding Num, StringFormat=...}" />

Thanks.


Solution

  • Try using a converter:

    public class StringToDoubleConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            return double.Parse(value as string);
        }
    
        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
    

    Then in xaml, declare the converter:

    <UserControl.Resources>
        <local:StringToDoubleConverter x:Key="StringToDoubleConverter"/>
    </UserControl.Resources>
    

    And finally use it in the binding, together with the StringFormat:

    <TextBlock Text= "{Binding Num, StringFormat=n0, Converter={StaticResource StringToDoubleConverter}}" />
    

    The zero in n0 indicates no decimal places (Standard Numeric Format Strings)