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\}}"/>
As far as I'm aware StringFromat is Silverlight 4 function, Silverlight for Windows Phone 7.0 is basically Silverlight 3 + some extras. I guess no then.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With