Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Formatting a date in XAML on WP7

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'

like image 809
Mark Avatar asked Jan 14 '11 19:01

Mark


2 Answers

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\}}"/>
like image 79
Aaron McIver Avatar answered Sep 23 '22 15:09

Aaron McIver


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.

like image 33
Lukasz Madon Avatar answered Sep 23 '22 15:09

Lukasz Madon