Highlighting dates in UWP CalendarView

WinUI

4 years ago

I have posted about UWP CalendarView control a while back. The previous post summarized how to customize calendar days while they are being assigned. A new StackOverflow question has prompted me to revisit this to show how already displayed dates can be adjusted as well.

Setting the scene

Consider the following simple XAML markup:

What we will want to do is to let the user pick dates via the DatePicker and highlight them in the CalendarView.

Date highlighting

First will keep the selected dates in a collection of DateTimeOffset instances in the code-behind:

When the user clicks the add button, we execute the following:

The key logic will be in the UpdateCalendar method. This must enumerate all the currently displayed dates and ensure the ones which the user selected are highlighted. Unfortunately, CalendarView does not provide a friendly "Dates" or "Items" property so to get the individual CalendarViewDayItem instances, we will have to use VisualTreeHelper to crawl the visual tree of the calendar control and find all controls of given type. While the implementation is not that complex, its even better to avoid reinventing the wheel and just use the FindDescendants<T> extension method from Windows Community Toolkit! First - install the Microsoft.Toolkit.Uwp.UI from NuGet:

Adding Toolkit NuGet

Once installed, add the following using declaration to the top of your code-behind:

And now let's use it!

We find all CalendarViewDayItem children of CalendarView, enumerate them and then check if the date matches one of the user selections. If yes, we highlight it. Conversely, we unhighlight (that is because the CalendarViewDayItem instances are reused, so we have to make sure their state is always set properly). The highlight methods are very simple:

Finally, we apply the knowledge from the previous blog post and handle the CalendarViewDayItemChanging event:

This is essentially the same thing logic as in UpdateCalendar, but here we are directly given a specific CalendarViewDayItem to work with.

Sample code

The example project is available on my GitHub.

CalendarView highlighting

CalendarView highlighting