C# WPF Tutorial – Calendar

0
966

WPF Calendar is a UI component which is used to represent data, time or took input from users as date, and time. We often fill out forms to put our information for different purposes and we saw a DOB, or Date of Birth field in which we saw calendars to select the exact date, year & month.

WPF Calendar provides a simple navigation to figure out the date, month and year. You can use mouse and keyboard events on it also.

There are two ways to add WPF Calendar to your application, either by dragging and dropping from ToolBox or by manually writing xaml code. As the following code will generate a calendar in your main window.

XAML Code:

<StackPanel>
<Calendar x:Name="calendar"/>
</StackPanel>

Output: The above code generates exact same output as you can observe in the image.

C# WPF Tutorial – Calendar - example output

If you don’t want to show some of the dates to be selectable you can use BlackoutDates property.

XAML Code:

<StackPanel>
<Calendar x:Name="calendar">
<Calendar.BlackoutDates>
<CalendarDateRange Start="9/1/2022" End = "9/10/2022"/>
<CalendarDateRange Start="9/21/2022" End = "9/25/2022"/>
</Calendar.BlackoutDates>
</Calendar>
</StackPanel>

Output: The above code will make those dates disabled so the user can’t select those, which you can observe in the following image.

C# WPF Tutorial – Calendar - BlackoutDates example output

Note: Formate for BlackoutDates is Month/Day/Year

If you want to preselect a single date or multiple dates you can use SelectedDates property. For single-date preselection, you can use the following code.

<StackPanel>
<Calendar x:Name="calendar">
<Calendar.SelectedDates>
<sys:DateTime>9/5/2022</sys:DateTime>
</Calendar.SelectedDates>
</Calendar>
</StackPanel>

If you want to preselect multiple dates you can use the following code.

<StackPanel>
<Calendar x:Name="calendar" SelectionMode = "MultipleRange">
<Calendar.SelectedDates>
<sys:DateTime>9/5/2022</sys:DateTime>
<sys:DateTime>9/6/2022</sys:DateTime>
</Calendar.SelectedDates>
</Calendar>
</StackPanel>

Note: For multiple selections, you need to change the selection mode as above.

Output: We are not adding an individual image, so the following image represents a single and multiple selection of dates in the calendar.

C# WPF Tutorial – Calendar - SelectedDates example output

Watch the following video for depth knowledge of the WPF Calendar:

If you have any kind of questions left, feel free to contact me.