【发布时间】:2011-01-14 19:27:12
【问题描述】:
有没有办法为 Windows Phone 7 使用 XAML 格式化日期?
如果尝试使用:
<TextBlock Text="{Binding Date, StringFormat={}{0:MM/dd/yyyy}}" />
但我得到了错误:
在“绑定”类型中找不到属性“StringFormat”
【问题讨论】:
标签: xaml windows-phone-7
有没有办法为 Windows Phone 7 使用 XAML 格式化日期?
如果尝试使用:
<TextBlock Text="{Binding Date, StringFormat={}{0:MM/dd/yyyy}}" />
但我得到了错误:
在“绑定”类型中找不到属性“StringFormat”
【问题讨论】:
标签: xaml windows-phone-7
在 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\}}"/>
【讨论】:
据我所知,StringFromat 是 Silverlight 4 功能,Silverlight for Windows Phone 7.0 基本上是 Silverlight 3 + 一些附加功能。那估计不行了。
【讨论】:
这可能是您正在寻找的。 RelativeDateTimeConverter
【讨论】: