#1,038 – Another Way to Prevent Certain Dates from Being Selected

You can limit the dates available for selection in a Calendar or DatePicker control in a few different ways.

If you want to prohibit some combination of dates, but have to do some calculation to figure out which dates should be prohibited, you can add a handler for the SelectedDateChanged event.

        <Label Content="Pick a day to go skydiving:"
               Margin="5"/>
        <DatePicker Margin="5,0,5,5"
                    SelectedDateChanged="DatePicker_SelectedDateChanged" />

In the handler, if the selected date is not one that you allow, you can undo the fact that it was selected.

        private void DatePicker_SelectedDateChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
        {
            if (e.AddedItems.Count > 0)
            {
                DateTime dayToDive = (DateTime)e.AddedItems[0];
                if ((dayToDive.DayOfWeek == DayOfWeek.Friday) &&
                    (dayToDive.Day == 13))
                {
                    MessageBox.Show("Dude, that's really an unlucky day to go skydiving.");
                    ((DatePicker)sender).SelectedDate = null;
                }
            }
        }

If we pick a Friday the 13th, the application warns us and then unselects the date.
1038-001

 

1038-002

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

One Response to #1,038 – Another Way to Prevent Certain Dates from Being Selected

  1. Overlord says:

    How can I make it generic, say I enter any date range (For eg. 1900/1/1 to 2020/1/1) and the code will blackout all weekends form that range.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: