Is there a way to format a date using XAML for Windows Phone 7?
If tried using:
<TextBlock Text="{Binding Date, StringFormat={}{0:MM/dd/yyyy}}" /> But I get the error:
The property 'StringFormat' was not found in type 'Binding'
Within SL4 this is possible...
<TextBlock Text="{Binding Date, StringFormat='MM/dd/yyyy'}}"/> ...within SL3 you would need to make use of an IValueConverter.
public class DateTimeToStringConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { return String.Format("{0:MM/dd/yyyy}", (DateTime)value); } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } If you wanted a more robust approach you could make use of the ConverterParameter.
public class DateTimeToStringConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if (parameter == null) return ((DateTime)value).ToString(culture); else return ((DateTime)value).ToString(parameter as string, culture); } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } Then in your XAML you would first define the converter as a resource...
<namespace:DateTimeToStringConverter x:Key="MyDateTimeToStringConverter"/> ..then reference it along with an acceptable parameter for formatting the DateTime value...
<TextBlock Text="{Binding Date, Converter={StaticResource MyDateTimeToStringConverter}, ConverterParameter=\{0:M\}}"/>