开发者

XAML TextBlock XML: StringFormat to display number

开发者 https://www.devze.com 2023-04-12 10:02 出处:网络
My XML data is: <Num>12.6</Num> I bind this to a XAML TextBlock and want to display the v开发者_如何学运维alue as a rounded number without decimal point. So this value should be display

My XML data is:

<Num>12.6</Num>

I bind this to a XAML TextBlock and want to display the v开发者_如何学运维alue 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.


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)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号