开发者

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 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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜