以下的範例就是配合了前一篇文章的程式碼作修改,能夠限制使用者不能在前後一個月或三個月內選擇星期二和星期五。修改後的畫面如下圖:
在圖中你可能看到星期二和星期五已被禁止選擇,至於主要修改的地方是MainPage.xaml.cs,下面是相關的程序碼:
1: using System;
2: using System.Windows.Controls;
3: using System.Collections.Generic;
4:
5: namespace DatePicker1_1
6: {
7: public partial class MainPage : UserControl
8: {
9: public MainPage()
10: {
11: InitializeComponent();
12: SetDisplayDateRange(1); //預設可選前後三個月內的日期
13: }
14:
15: private void SetDisplayDateRange(int month = 3)
16: {
17: //每月的最後一日
18: int[] EndDayOfYear = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
19:
20: DateTime StartDate = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1);
21: StartDate = StartDate.AddMonths(-month);
22:
23: DateTime EndDate = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1);
24: EndDate = EndDate.AddMonths(month);
25:
26: if (DateTime.IsLeapYear(EndDate.Year))
27: {
28: EndDayOfYear[1] = 29; //如果是Leap Year, 二月要是29日
29: }
30:
31: EndDate = new DateTime(EndDate.Year, EndDate.Month, EndDayOfYear[EndDate.Month - 1]);
32:
33: datePicker1.DisplayDateStart = (StartDate).Date;
34: datePicker1.DisplayDateEnd = (EndDate).Date;
35:
36: try
37: {
38: // 禁止選擇所有星期二和星期五的日期
39: int DayRange = EndDate.Subtract(StartDate).Days + 1;
40:
41: for (int i = 0; i < DayRange; i++)
42: {
43: if (StartDate.AddDays(i).DayOfWeek == DayOfWeek.Tuesday || StartDate.AddDays(i).DayOfWeek == DayOfWeek.Friday)
44: {
45: datePicker1.BlackoutDates.Add(new CalendarDateRange(StartDate.AddDays(i), StartDate.AddDays(i)));
46: }
47: }
48: }
49: catch (Exception x)
50: {
51: // Statements for handling the exception
52: System.Windows.MessageBox.Show(x.Message.ToString());
53: }
54: }
55:
56: private void button1_Click(object sender, System.Windows.RoutedEventArgs e)
57: {
58: SetDisplayDateRange(1); //呼叫function限制可選前後一個月內的日期
59: }
60:
61: private void button2_Click(object sender, System.Windows.RoutedEventArgs e)
62: {
63: SetDisplayDateRange(); //呼叫function還原可選前後三個月內的日期
64: }
65:
66: }
67: }
主要修改部份在Try{ }Catch 內,先用.Subtract去計算StartDate 和EndDate該段日期之間有多少日,然後透過for loop去決定該段日期內的日子是否星期二或星期五。如果條件符合,會使用DatePicker1元件的BlackoutDates.add方法去設定該日禁止選取。
完整的程序碼地址供下載參考:
https://docs.google.com/open?id=0BxRiNrIXEFArMWR0WXM2eFlUSEsxVVpnUFZkZGljdw
有出錯請回覆我 :)
沒有留言:
張貼留言