Formatting a date in XAML on WP7

2019-01-17 18:12发布

问题:

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'

回答1:

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\}}"/>


回答2:

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.



回答3:

This is probably what you are looking for. RelativeDateTimeConverter