使用WPF日期选择器的时间差 [英] date difference using datepicker in wpf

查看:337
本文介绍了使用WPF日期选择器的时间差的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试着去计算多少天有两个日期之间,并在文本块中显示结果,我使用WPF。不过,我得到一个可空对象必须在第一行的值:•

 私人无效button20_Click(对象发件人,RoutedEventArgs E) 
{
日期时间开始= datePicker1.DisplayDateStart.Value.Date;
日期时间完成= datePicker2.DisplayDateStart.Value.Date;
时间跨度差异= start.Subtract(完成);
textBlock10.Text = Convert.ToString(差);
}


解决方案

随着错误消息意味着, DisplayDateStart 是一个可为空的属性,这意味着它可以(在默认情况下的确实的),没有任何价值。你必须处理这种情况不能产生有意义的结果。



这表示, DisplayDateStart 属性是指最早日期在的DatePicker的日历中显示,而不是用户已经选择了日期:为此,你需要在 SelectedDate 属性,它也可为空



有很多种,你可以处理NULL值的方式:在文本块就什么都不显示,显示N / A或其他一些默认情况下,等这里有一个例子:

 私人无效button20_Click(对象发件人,RoutedEventArgs E)
{
//此块设置文本块到一个合理的默认日期是否避风港 ŧ被采摘
如果
{
textBlock10.Text =选择日期(datePicker1.SelectedDate.HasValue || datePicker2.SelectedDate.HasValue!);
的回报;
}

//因为可空SelectedDate属性必须有一个值来达到这一点,
//我们可以放心地引用它们 - 否则,这些语句扔了,因为你已经发现的。
日期时间开始= datePicker1.SelectedDate.Value.Date;
日期时间完成= datePicker2.SelectedDate.Value.Date;
时间跨度差异= finish.Subtract(开始);
textBlock10.Text = difference.TotalDays.ToString();
}


Im trying to calculate the how many days there are between two dates and display the result in a textblock, i am using wpf. However i get a nullable object must have a value in the first line :S

    private void button20_Click(object sender, RoutedEventArgs e)
    {
        DateTime start = datePicker1.DisplayDateStart.Value.Date;
        DateTime finish = datePicker2.DisplayDateStart.Value.Date;
        TimeSpan difference = start.Subtract(finish);
        textBlock10.Text = Convert.ToString(difference);
    }

解决方案

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();
}

这篇关于使用WPF日期选择器的时间差的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆