在WP7上格式化XAML中的日期

时间:2011-01-14 19:27:13

标签: xaml windows-phone-7

有没有办法使用XAML为Windows Phone 7格式化日期?

如果尝试使用:

<TextBlock Text="{Binding Date, StringFormat={}{0:MM/dd/yyyy}}" />

但我收到错误:

在'Binding'

类型中找不到属性'StringFormat'

3 个答案:

答案 0 :(得分:20)

在SL4中,这是可能的......

<TextBlock Text="{Binding Date, StringFormat='MM/dd/yyyy'}}"/>

...在SL3中,您需要使用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();
    }
}

如果您想要更强大的方法,可以使用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();
        }
    }

然后在您的XAML中,您首先将转换器定义为资源...

<namespace:DateTimeToStringConverter x:Key="MyDateTimeToStringConverter"/>

..然后引用它以及用于格式化DateTime值...

的可接受参数
<TextBlock Text="{Binding Date, 
         Converter={StaticResource MyDateTimeToStringConverter}, 
         ConverterParameter=\{0:M\}}"/>

答案 1 :(得分:2)

据我所知,StringFromat是Silverlight 4的功能,Silverlight for Windows Phone 7.0基本上是Silverlight 3 +一些附加功能。我想不是。

答案 2 :(得分:0)

这可能就是你要找的东西。 RelativeDateTimeConverter