Search code examples
c#wpfinputtextbox

TextBox : Modify user's input


When the user adds a ;, I want to add ; + Environment.NewLine in the TextBox.

I find this solution :

private void TextBox_OnPreviewTextInput(object sender, TextCompositionEventArgs e)
{
    if (e.Text == ";")
    {
        e.Handled = true;
        TextCompositionManager.StartComposition(
                new TextComposition(InputManager.Current,
                (IInputElement)sender,
                ";" + Environment.NewLine)
        );
    }
}

But after this, the undo don't work.

Can you explain me how control the user input and keep the undo stack?


Solution

  • -------------- Updated Code As Requested ---------

    Use this Instead and 100% it's work. I test it for assurance.

    private void TextBox_OnPreviewTextInput(object sender, TextCompositionEventArgs e)
    {
        if (e.Text == ";")
        {
            // In this line remove preview event to  preventing event repeating
            ((TextBox)sender).PreviewTextInput -= TextBox_OnPreviewTextInput;
    
            // Whith this code get the current index of you Caret(wher you inputed your semicolon)
            int index = ((TextBox)sender).CaretIndex;
    
            // Now do The Job in the new way( As you asked)
            ((TextBox)sender).Text = ((TextBox)sender).Text.Insert(index, ";\r\n");
    
            // Give the Textbox preview Event again
            ((TextBox)sender).PreviewTextInput += TextBox_OnPreviewTextInput;
    
            // Put the focus on the current index of TextBox after semicolon and newline (Updated Code & I think more optimized code)
            ((TextBox)sender).Select(index + 3, 0);
    
            // Now enjoy your app
             e.Handled = true;
        }
    }
    

    Wish you bests , Heydar