Windows Phone 7 – No StringFormat in DataBinding
July 20, 2011A very handy feature that is available in WPF and Silverlight 4 is the possibility to specify a StringFormat attribute in data binding expressions. This way, custom formatting of data members can be done easily so that these data members get the appropriate visual representation in your application. This is especially useful for Double or DateTime data members, where the default ToString representation is often not the desired one.This expression, for example, displays a Double value with a fixed number of two decimal places:
<TextBlock Text="{Binding SomeValue, StringFormat=\{0:0.00\} }" />
Unfortunately, this feature is not available in Silverlight 3 and therefore not for Window Phone 7.However, there is a simple solution to this problem in form of a custom IValueConverter that can do the trick.The class has a property Format that receives the actual format string.
public class FormatConverter : IValueConverter { public FormatConverter() { Format = "{0}"; } public string Format { get; set; } public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { var d = (double)value; var s = string.Format(Format, d); return s; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } }
The only things that remain to be done it to create an instance of the converter in the Resources section of your page …
<phone:PhoneApplicationPage.Resources> <u:FormatConverter x:Key="formatConverter" Format="{}{0:0.00}"/> </phone:PhoneApplicationPage.Resources>
… and use it in your binding expression.
<TextBlock Text="{Binding Path=SomeValue, Converter={StaticResource formatConverter}}"/>
A both generic and simple solution to a reoccurring problem.