我有一个数据网格,我显示可以为空的日期值。但是,在保存dataGrid上的记录时,如果我没有提供日期,则会抛出错误 {" SqlDateTime溢出。必须在1/1/1753 12:00:00 AM和12/31/9999 11:59:59 PM之间。"} 此外,在xaml上,如果我选择日期,它甚至不会显示日期。
XAML :
<DataGridTemplateColumn Header="MyDate">
<DataGridTemplateColumn.CellEditingTemplate>
<DataTemplate>
<xcd:DateTimePicker Value="{Binding MyDate, ValidatesOnDataErrors=True, UpdateSourceTrigger=PropertyChanged, Converter={StaticResource MinDateToNullConverter}}"/>
</DataTemplate>
</DataGridTemplateColumn.CellEditingTemplate>
</DataGridTemplateColumn>
对象:
public DateTime? MyDate
{
get { return GetProperty(MyDateProperty); }
set { SetProperty(MyDateProperty, value); }
}
LoadProperty(MyDateProperty, dr.GetDateTime("MyDate"));
cmd.Parameters.AddWithValue("@MyDate", ReadProperty(MyDateProperty).ToDBNull());
转换器:
[ValueConversion(typeof(SmartDate), typeof(DateTime?))]
public class MinDateToNullConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (targetType == typeof(DateTime?) && value != null && !string.IsNullOrEmpty(value.ToString()))
{
SmartDate theValue = value is SmartDate ? (SmartDate)value : new SmartDate(value.ToString());
if (theValue == DateTime.MinValue)
return null;
else
return theValue;
}
else
{
return null;
}
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value == null)
{
return DateTime.MinValue;
}
else
{
return value;
}
}
}