I am working on Windows 10 Universal app and I am confused on how to implement DatePicker on textbox tap. As soon I click on Textbox I want datepicker to showup. I have tried Tapped and OnFocus event and call datepicker using C# but that didn't help. Is their any other way to implement it.
The CalendarDatePicker in UWP in an actual UI Control. Which means it got it's own event, UI and ways to be used.
Which means that if I add a simple CalendarDatePicker to my UI like this:
var picker = new CalendarDatePicker();
mainGrid.Children.Add(picker);
I would produce a control like this:
And if I press the "select a date" button:
My recommendation is to use that instead, since they've already solved a lot of problems and created everything for you. BUT, if you really want to use your own TextBox, nothing is stopping you from doing that. It's just a bit more cumbersome.
This is one option to use to make a Calendar view show up when you focus a TextBox:
private void CalendarDatePicker_DateChanged(CalendarDatePicker sender, CalendarDatePickerDateChangedEventArgs args)
{
calendar.IsCalendarOpen = false;
textBox.Text = args.NewDate?.DateTime.ToString("dd/MM/yyyy");
}
private void textBox_GotFocus(object sender, RoutedEventArgs e)
{
calendar.IsCalendarOpen = true;
}
And the corresponding XAML:
<TextBox x:Name="textBox" PlaceholderText="Press me!" Tapped="Btn_Tapped" GotFocus="textBox_GotFocus" Height="100" />
<CalendarDatePicker x:Name="calendar" Width="0" Height="0" DateChanged="CalendarDatePicker_DateChanged" />
PS. The trick is to set the CalendarDatePicker Height and Width to zero, that makes the actual button invisible, but still lets the Calendar flyout be visible when setting IsCalendarOpen = true
I hope that helps. Would love to hear feedback or critique about the answer :)
Have a good day!