1

Regular expression should check and change datapicker text after input. I'm using keyUp event for this.

private void DatePicker_KeyUp(object sender, RoutedEventArgs e)
{
    DatePicker dp = (sender as DatePicker);
    string text = dp.Text;
    if (Regex.IsMatch(text, @"^\d{3}"))
    {
        dp.Text = Regex.Replace(text, @"(\d{2})(\d)", "$1.$2");
    }
    else if (Regex.IsMatch(text, @"^(\d{2}\.\d{3})"))
    {
        dp.Text = Regex.Replace(text, @"(\d{2}\.\d{2})(\d)", "$1.$2");
    }
}

But dp.Text doesn't set text. Does anybody have an idea how to write text to datapicker or some another way to add separating dots while writing?

M. Krotov
  • 15
  • 6
  • 5
    Possible duplicate of [Changing the string format of the WPF DatePicker](https://stackoverflow.com/questions/3819832/changing-the-string-format-of-the-wpf-datepicker) – Flater Sep 28 '17 at 10:14
  • Your event handler sets the Text when there is actually a match against your regular expression. So what is your actual issue? – mm8 Sep 28 '17 at 10:20
  • after typing 'ddm' event handler should set datapicker's text to ("dd.m"), but that's invalid string so it sets it as empty – M. Krotov Sep 28 '17 at 10:30

1 Answers1

1

You could try to handle the PreviewTextInput event and set the Text property of the DatePickerTextBox:

private void DatePicker_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
    DatePicker dp = (sender as DatePicker);
    string text = dp.Text + e.Text;
    if (Regex.IsMatch(text, @"^\d{3}"))
    {
        e.Handled = true;
        DatePickerTextBox tb = dp.Template.FindName("PART_TextBox", dp) as DatePickerTextBox;
        tb.Text = Regex.Replace(text, @"(\d{2})(\d)", "$1.$2");
        tb.CaretIndex = tb.Text.Length;
    }
    else if (Regex.IsMatch(text, @"^(\d{2}\.\d{3})"))
    {
        e.Handled = true;
        DatePickerTextBox tb = dp.Template.FindName("PART_TextBox", dp) as DatePickerTextBox;
        tb.Text = Regex.Replace(text, @"(\d{2}\.\d{2})(\d)", "$1.$2");
        tb.CaretIndex = tb.Text.Length;
    }
}
mm8
  • 163,881
  • 10
  • 57
  • 88