Search code examples
c#regexwpfxamltextbox

Can't replace selected regex number by type next number


I'm using xaml <TextBox/> with code behind which contains event PreviewTextchanged named NumberValidationTextBox and event TextChanged named OnTextChanged:

    public void NumberValidationTextBox(object sender, TextCompositionEventArgs e)
    {
        Regex regex = new Regex("^-?[0-9]*[\\.,]?[0-9]?[0-9]?$");
        var futureText = $"{(sender as TextBox).Text}{e.Text}";
        e.Handled = !regex.IsMatch(futureText);

    }
    private void OnTextChanged(object sender, TextChangedEventArgs e)
    {
        var myInput = sender as TextBox;
        myInput.Text = myInput.Text.Replace(",", ".").Trim();
        myInput.CaretIndex = myInput.Text.Length;
    }

Problem is when typed number is for example: 123.23, and I select the number by click and mouse drag and try to replace it by type next number - it don't changes, because regex is blocking it. Only using Backspace is the solution in this case. So I want to change the selected text when the TextBox is filled.

All detais above and here link with ss: https://i.ibb.co/z7rPfpj/123.png

How to fix it? Thanks.


Solution

  • Replace your method NumberValidationTextBox by:

        public void NumberValidationTextBox(object sender, TextCompositionEventArgs e)
        {
            Regex regex = new Regex("^-?[0-9]*[\\.,]?[0-9]?[0-9]?$");
            var tb = sender as TextBox;
            var futureText = "";
            if (tb.SelectedText != "")
            {
                futureText = tb.Text.Replace(tb.SelectedText, e.Text);
                e.Handled = !regex.IsMatch(futureText);
                return;
            }
    
            futureText = tb.Text + e.Text;
            e.Handled = !regex.IsMatch(futureText);
        }
    

    you test SelectedText to check if some chars are selected