有没有一种方法可以使用XAML格式化Windows Phone 7中的日期?
我尝试使用:
<TextBlock Text="{Binding Date, StringFormat={}{0:MM/dd/yyyy}}" />
但是我遇到了错误:
属性“StringFormat”在类型“Binding”中未找到。
有没有一种方法可以使用XAML格式化Windows Phone 7中的日期?
我尝试使用:
<TextBlock Text="{Binding Date, StringFormat={}{0:MM/dd/yyyy}}" />
在 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\}}"/>
<namespace:DateTimeToStringConverter x:Key="MyDateTimeToStringConverter"/>
请问你有没有完整的示例可以从头到尾演示如何实现这个?错误显示为“DateTimeToStringConverter未找到”。 - webdad3