关于产生错误
“The as operator must be used with a reference type or nullable type ('System.DateTime' is a non-nullable value type) ”
今天写数据转换器,需要将按照时间值显示不同的时间格式字符串。
结果在Convert里发现这么写报错。
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
DateTime time = value as DateTime;
}
该问题是因为DateTime 为值类型,不能用引用类型或空类型。我们可以按如下方法写这段代码。
//DateTime time = value as DateTime; 这种写法就不对 因为DateTime为值类型
//DateTime time = value as DateTime? ?? _NullTime; 这种写法虽然不报错用起来也没问题,不过也不合适
DateTime time = (DateTime)value; //这种是正确写法 多谢阿干童鞋指正
贴一下这个数据转换器
需求:
绑定时间为当日的 只显示“时:分”
绑定时间为当年且当日前的 显示 “月-日 时:分”
绑定时间为往年的 显示 “年份 月-日 时:分”
数据转换器:
public class TimeFormatConverter:IValueConverter{private static DateTime _Now = DateTime.Now;private static DateTime _UndefineTime = new DateTime(0);public object Convert(object value, Type targetType, object parameter, CultureInfo culture){//DateTime time = value as DateTime;//DateTime time = value as DateTime? ?? _NullTime;DateTime time = (DateTime)value;if (time == _UndefineTime)return "绑定时间有误";int offYear = _Now.Year - time.Year;int offDay = _Now.Date.Subtract(time.Date).Days;if (offYear >= 1){return string.Format("{0:yyyy-MM-dd HH:mm}", time);}else if (offDay >= 1){return string.Format("{0:MM-dd HH:mm}", time);}else{return string.Format("{0:HH:mm}", time);}}public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture){throw new NotImplementedException();}}
xaml中声明集合
xmlns:Conv="clr-namespace:MyPageTabDemo.Utils.Converter"
使用
<TextBlock Text="{Binding Timestamp, Converter={StaticResource TimeFmtConverter}}" .../>