check if age is <18 datepicker wpf
我正在制作一个用户必须超过18岁的应用程序。如果他/她还不到18岁,那么
我的代码如下:
XAML
1 | <DatePicker HorizontalAlignment="Center" Name="dpkDOB" Grid.Column="1" VerticalAlignment="Top" Grid.Row="1" /> |
厦门
1 2 3 4 5 | int age = DateTime.Today.Year - tbkDOB.Value.Year; if (age < 18) { MessageBox.Show("Under age"); } |
我在Visual Studio中测试过。请找到以下工作代码:
XAML:
1 2 3 | <DatePicker HorizontalAlignment="Center" Name="dpkDOB" Grid.Column="1" VerticalAlignment="Top" Grid.Row="1" SelectedDateChanged="dpkDOB_SelectedDateChanged"/> |
XAML.cs:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | 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); } |