正如错误消息所暗示的那样,DisplayDateStart
是一个可为空的属性,这意味着它可以(并且默认情况下确实)没有值。您必须处理这种情况才能产生合理的结果。
也就是说,该DisplayDateStart
属性指的是 DatePicker 日历中显示的最早日期,而不是用户选择的日期:为此,您需要该SelectedDate
属性,该属性也可以为空。
有多种方法可以处理 NULL 值:在 TextBlock 中不显示任何内容、显示“N/A”或其他默认值等。这是一个示例:
private void button20_Click(object sender, RoutedEventArgs e)
{
// This block sets the TextBlock to a sensible default if dates haven't been picked
if(!datePicker1.SelectedDate.HasValue || !datePicker2.SelectedDate.HasValue)
{
textBlock10.Text = "Select dates";
return;
}
// Because the nullable SelectedDate properties must have a value to reach this point,
// we can safely reference them - otherwise, these statements throw, as you've discovered.
DateTime start = datePicker1.SelectedDate.Value.Date;
DateTime finish = datePicker2.SelectedDate.Value.Date;
TimeSpan difference = finish.Subtract(start);
textBlock10.Text = difference.TotalDays.ToString();
}