I have a datepicker control on a wpf form (masked as 00-00-0000). If the datepicker is empty, then I want the cursor always to be in the first position no matter where I click on the datepicker textbox. I tried using SelectionStart property (set to 0) on MouseDown event but it didn't work. Can anyone please give an idea? Please let me know if you need more info. Any help is much appreciated. Thanks!
You should find TextBox
element and subscribe to event PreviewMouseUp
.
1) Add DatePicker
with Loaded
event:
<DatePicker Name="myDatePicker" Loaded="MyDatePicker_OnLoaded" />
2) Find TextBox
element (in the DatePicker
type of the text box element is DatePickerTextBox
) and subscribe to PreviewMouseUp
:
private void MyDatePicker_OnLoaded(object sender, RoutedEventArgs e)
{
var tb = (DatePickerTextBox)myDatePicker.Template.FindName("PART_TextBox", myDatePicker);
if (tb != null)
{
tb.PreviewMouseUp += (s, args) =>
{
tb.CaretIndex = 0;
};
}
}