检查年龄是否<18 datepicker wpf

时间:2016-07-28 10:46:00

标签: c# wpf

我正在制作一个用户必须超过18的应用程序。如果他/她小于18,messageBox出现“不足年龄”。我正在使用datePicker来选择用户D.O.B.我的问题是我不完全确定如何编写代码,但我通过查看教程给了它一个但是所有的教程似乎都是dateTimePickers

我的代码如下:

XAML

<DatePicker HorizontalAlignment="Center" Name="dpkDOB" Grid.Column="1" VerticalAlignment="Top" Grid.Row="1" />

xaml.cs

 int age = DateTime.Today.Year - tbkDOB.Value.Year;
 if (age < 18)
 {
     MessageBox.Show("Under age");
 }

1 个答案:

答案 0 :(得分:2)

我在visual studio中测试过。请找到以下工作代码:

XAML:

<DatePicker HorizontalAlignment="Center" Name="dpkDOB" Grid.Column="1" 
   VerticalAlignment="Top" Grid.Row="1" 
   SelectedDateChanged="dpkDOB_SelectedDateChanged"/>

XAML.cs:

public MainWindow()
{
    InitializeComponent();
}

private void dpkDOB_SelectedDateChanged(object sender, SelectionChangedEventArgs e)
{
    var ageInYears = GetDifferenceInYears(dpkDOB.SelectedDate.Value, DateTime.Today);
    if (ageInYears < 18)
    {
        MessageBox.Show("Under age");
    }
}

int GetDifferenceInYears(DateTime startDate, DateTime endDate)
{
    return (endDate.Year - startDate.Year - 1) +
        (((endDate.Month > startDate.Month) ||
        ((endDate.Month == startDate.Month) && (endDate.Day >= startDate.Day))) ? 1 : 0);
}