1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【C#】【WPF】カレンダーコントロールで選択不可日を指定する

Last updated at Posted at 2019-08-06

UIとしてカレンダーで日付を選択させる際に
選択可能な範囲を制限したいケースがあると思います。
#過去日付は選択不可とか

で、その場合にどうするかというと
選択できない日付を設定するためにBlackoutDatesプロパティを使用します。

単純に過去日付を選択不可にする場合は以下でOK。

現在日より過去を選択不可にする
    // 過去を選択不可能にする
    calendar.BlackoutDates.AddDatesInPast();

選択不可にする日付を具体的に指定したい場合は以下のように指定します。

選択不可日付を指定する場合
    // 2019年8月1日~8月31日を選択不可能にする
    calendar.BlackoutDates.Add(new DateTime(2019, 8, 1), new DateTime(2019, 8, 31));

    // 2019年9月1日を選択不可能にする
    calendar.BlackoutDates.Add(new DateTime(2019, 9, 1));

で、実際使用した際に起きた問題についても記載しておきます。
日付が変わったタイミングで動的に選択範囲を切り替えるような処理を組んでいたのですが、
その際にOutOfRangeException(範囲外エラー)が発生してしまうことがありました。
何故だ…と思っていましたが、原因がわかると実にシンプルでした。

例えば上記の例で、2019年8月1日~8月31日を選択不可能にする処理を実行した際に
カレンダーコントロールが指定している値が
『2019年7月31日』になっているとエラーになります。
つまり、範囲設定を行った際に現在の値が指定範囲外になっているとエラー。
確かに範囲外だわ…。

なので範囲指定を行う際は現在値もチェックしてあげると安全です。

範囲チェックしてから選択
var inputRange = new CalendarDateRange( new DateTime(2019, 8, 1), new DateTime(2019, 8, 31) );
if (inputRange.End < calendar.SelectedDate)
{
	// 選択不可範囲を指定しているとエラーになるので補正
	// (範囲終端を超えているので終端の日付に補正)
	calendar.SelectedDate = inputRange.End;
}
else if (calendar.SelectedDate < inputRange.Start)
{
	// 選択不可範囲を指定しているとエラーになるので補正
	// (範囲先端をより過去なので先端の日付に補正)
	calendar.SelectedDate = inputRange.Start;
}
// 2019年8月1日~8月31日を選択不可能にする
calendar.BlackoutDates.Add(inputRange);
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?