有沒有辦法使用Windows Phone 7的XAML格式化日期?在WP7上格式化XAML中的日期
如果嘗試使用:
<TextBlock Text="{Binding Date, StringFormat={}{0:MM/dd/yyyy}}" />
但我得到的錯誤:
的財產 '的StringFormat' 型 '綁定'
有沒有辦法使用Windows Phone 7的XAML格式化日期?在WP7上格式化XAML中的日期
如果嘗試使用:
<TextBlock Text="{Binding Date, StringFormat={}{0:MM/dd/yyyy}}" />
但我得到的錯誤:
的財產 '的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"/>
..then在可接受的參數引用它沿着格式化DateTime
值...
沒有被發現就我所知StringFromat是Silverlight 4的功能,Silverlight for Windows Phone 7.0基本上是Silverlight 3 +的一些額外功能。那我就沒有了。
作品,因爲芒果 – 2012-01-10 18:22:22
這可能是你在找什麼。 RelativeDateTimeConverter
+1但是一些建議:包括使用實例,利用ConverterParameter以另一種方式是字符串傳遞,爲類提供一個名稱更符合其功能保持說「DateTimeToStringConverter」。 – AnthonyWJones 2011-01-14 20:52:48