有没有办法使用 XAML for Windows Phone 7 格式化日期?
如果尝试使用:
<TextBlock Text="{Binding Date, StringFormat={}{0:MM/dd/yyyy}}" />
但我得到了错误:
在“绑定(bind)”类型中找不到属性“StringFormat”
最佳答案
在 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
值(value)...<TextBlock Text="{Binding Date,
Converter={StaticResource MyDateTimeToStringConverter},
ConverterParameter=\{0:M\}}"/>
关于xaml - 在 WP7 上用 XAML 格式化日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4695057/