26

How can I insert text into a WPF textbox at caret position? What am I missing? In Win32 you could use CEdit::ReplaceSel().

It should work as if the Paste() command was invoked. But I want to avoid using the clipboard.

Roice
  • 373
  • 1
  • 4
  • 8

5 Answers5

66

To simply insert text at the caret position:

textBox.Text = textBox.Text.Insert(textBox.CaretIndex, "<new text>");

To replace the selected text with new text:

textBox.SelectedText = "<new text>";

To scroll the textbox to the caret position:

int lineIndex = textBox.GetLineIndexFromCharacterIndex(textBox.CaretIndex);
textBox.ScrollToLine(lineIndex);
Tarsier
  • 2,329
  • 24
  • 17
17

If you want to move the caret after the inserted text the following code is useful

textBox.SelectedText = "New Text";
textBox.CaretIndex += textBox.SelectedText.Length;
textBox.SelectionLength = 0;
iyalovoi
  • 191
  • 1
  • 5
9

I found an even more simple solution by myself:

textBox.SelectedText = "New Text";
textBox.SelectionLength = 0;

Then scroll to the position as stated by Tarsier.

Roice
  • 373
  • 1
  • 4
  • 8
1

Late to the party, but I wrote this extension method, that inserts the text the same way as if you use the paste.

This handles MaxLength, CaretIndex and even Selection of text.

/// <summary>
/// Inserts text into this TextBox. Respects MaxLength, Selection and CaretIndex settings.
/// </summary>
public static void InsertText(this TextBox textBox, string value)
{
    // maxLength of insertedValue
    var valueLength = textBox.MaxLength > 0 ? (textBox.MaxLength - textBox.Text.Length + textBox.SelectionLength) : value.Length;
    if (valueLength <= 0)
    {
        // the value length is 0 - no need to insert anything
        return;
    }

    // save the caretIndex and create trimmed text
    var index = textBox.CaretIndex;
    var trimmedValue = value.Length > valueLength ? value.Substring(0, valueLength) : value;

    // if some text is selected, replace this text
    if (textBox.SelectionLength > 0)
    {
        index = textBox.SelectionStart;
        textBox.SelectedText = trimmedValue;
    }
    // insert the text to caret index position
    else
    {
        var text = textBox.Text.Substring(0, index) + trimmedValue + textBox.Text.Substring(index);
        textBox.Text = text;
    }

    // move caret to the end of inserted text
    textBox.CaretIndex = index + valueLength;
}
Gh61
  • 9,222
  • 4
  • 28
  • 39
0

Use TextBox.CaretIndex to modify the text bound to the TextBox.Text property.

Thorsten79
  • 10,038
  • 6
  • 38
  • 54