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?

3
  • 5
    Possible duplicate of Changing the string format of the WPF DatePicker Commented Sep 28, 2017 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? Commented Sep 28, 2017 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 Commented Sep 28, 2017 at 10:30

1 Answer 1

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;
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.