InvalidCastException when setting DatePicker SelectedDate property - 'Specified cast is not valid'
See original GitHub issueDescribe the bug
When trying to set SelectedDate property of DatePicker, an InvalidCastException is thrown.
Steps to reproduce the bug
- Create a new WinUI 3 in Desktop app (Reunion 0.5)
- Add a DatePicker to the MainWindow in a Grid like here:
<Grid Loaded="Grid_Loaded">
<DatePicker x:Name="datePicker"/>
</Grid>
- In the codebehind file, add the
Grid_Loadedhandler and set theSelectedDateproperty to a newDateTimeOffsetinstance:
private void Grid_Loaded(object sender, RoutedEventArgs e)
{
var timeOffset = new DateTimeOffset(new DateTime(2021,10,10);
datePicker.SelectedDate = timeOffset;
}
This should just work, but it throws an InvalidCastException when trying to set the SelectedDate property. The Date property works fine, but SelectedDate does not, so maybe it has something to do with Nullable<DateTimeOffset>, as that’s the type of the SelectedDate property, while the Date property is just of type DateTimeOffset.
Expected behavior
Selected date should be set without throwing an InvalidCastException.
Screenshots

Version Info
NuGet package version: [WinUI 3 - Project Reunion 0.5: 0.5.0]
Windows app type: Win32
| Windows 10 version | Saw the problem? |
|---|---|
| Insider Build (xxxxx) | |
| October 2020 Update (19042) | Yes |
| May 2020 Update (19041) | |
| November 2019 Update (18363) | |
| May 2019 Update (18362) | |
| October 2018 Update (17763) | |
| April 2018 Update (17134) | |
| Fall Creators Update (16299) | |
| Creators Update (15063) |
| Device form factor | Saw the problem? |
|---|---|
| Desktop | Yes |
| Xbox | |
| Surface Hub | |
| IoT |
Additional context
I was not able to reproduce that error on my SB2, but I was able to reproduce it on my desktop. Both have Windows 19042, I haven’t found out why it happens on one machine, but not on the other. But many people reached out to me because of this issue, and using Date property instead of SelectedDate property is a workaround.
Issue Analytics
- State:
- Created 2 years ago
- Comments:10 (10 by maintainers)

Top Related StackOverflow Question
For those looking for step-by-step:
Microsoft.Windows.CsWinRTNuGet package reference (1.1.4 or higher) to your project<CsWinRTEnabled>false</CsWinRTEnabled>@angelazhangmsft Agreed. Edited to prevent confusion.