As the error message implies, DisplayDateStart
is a nullable property, which means it can (and, by default, does) have no value. You have to handle this condition to produce sensible results.
That said, the DisplayDateStart
property refers to the earliest date shown in the DatePicker's calendar, not the date the user has picked: for that, you need the SelectedDate
property, which is also nullable.
There are a variety of ways you could handle a NULL value: display nothing in the TextBlock, display "N/A" or some other default, etc. Here's an example:
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();
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…