在 WP7 上以 XAML 格式格式化日期 [英] Formatting a date in XAML on WP7
问题描述
有没有办法在 Windows Phone 7 中使用 XAML 格式化日期?
Is there a way to format a date using XAML for Windows Phone 7?
如果尝试使用:
<TextBlock Text="{Binding Date, StringFormat={}{0:MM/dd/yyyy}}" />
但我收到错误:
在绑定"类型中找不到属性StringFormat"
The property 'StringFormat' was not found in type 'Binding'
推荐答案
在 SL4 中这是可能的...
Within SL4 this is possible...
<TextBlock Text="{Binding Date, StringFormat='MM/dd/yyyy'}}"/>
...在 SL3 中,您需要使用 IValueConverter.
...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();
}
}
如果您想要更强大的方法,您可以使用 ConverterParameter
.
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();
}
}
然后在您的 XAML 中,您首先将转换器定义为资源...
Then in your XAML you would first define the converter as a resource...
<namespace:DateTimeToStringConverter x:Key="MyDateTimeToStringConverter"/>
...然后将其与可接受的参数一起引用以格式化 DateTime
值...
..then reference it along with an acceptable parameter for formatting the DateTime
value...
<TextBlock Text="{Binding Date,
Converter={StaticResource MyDateTimeToStringConverter},
ConverterParameter=\{0:M\}}"/>
这篇关于在 WP7 上以 XAML 格式格式化日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!