Reputation: 429
I'm using the default WPF Datepicker control. I want the Calendar to open when the user selects the DP textbox, so that it's more clear they can also use the calendar to select a date. However, it seems that whenever the DP's textbox gets focus, it also closes the calendar popup.
If I use this simple function to open up the calendar, for example, the calendar opens, then closes, then sends an InvalidOperationException: "Cannot reopen a popup in the closed event handler." which implies to me that when a calendar opens it takes focus, then the textbox takes back focus and closes the popup, which then triggers the error.
private void DatePicker_GotKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
{
DatePicker d = sender as DatePicker;
d.IsDropDownOpen = true;
}
Any ideas on how to stop this mess and just have the calendar popup and the selected textbox live in peace?
Upvotes: 0
Views: 4280
Reputation: 91
You need to set StaysOpen="true"
on the Calendar
Use Blend to make a control template for the datepicker and then find "PART_Popup"
:
<Popup x:Name="PART_Popup"
AllowsTransparency="True"
Placement="Bottom"
StaysOpen="true" />
Upvotes: 1
Reputation: 4631
One way would be to create a UserControl that contains the following elements:
<DatePickerTextBox x:Name="TextBox" GotFocus="DatePickerTextBox_GotFocus" LostFocus="DatePickerTextBox_LostFocus"/>
<Button Click="Button_Click" Grid.Column="1">Pick</Button>
<Popup x:Name="MyPopup" StaysOpen="True" PlacementTarget="{Binding ElementName=TextBox}">
<Calendar Focusable="False"/>
</Popup>
And handle your custom logic regarding the Popup yourself. Be aware that this is not a trivial task, as you will need to:
It does give you the benefit of being able to customize the Popup further. For example, in solution I use at work, customers have requested a 'Today' button in the calendar. If you think having to maintain such a control is worth the effort, I can provide some details on our implementation, but if this is not an option for you, I won't post them yet.
Upvotes: 0