Reputation: 381
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.
Upvotes: 27
Views: 25788
Reputation: 9756
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;
}
Upvotes: 1
Reputation: 191
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;
Upvotes: 17
Reputation: 381
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.
Upvotes: 9
Reputation:
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);
Upvotes: 67
Reputation: 10128
Use TextBox.CaretIndex to modify the text bound to the TextBox.Text property.
Upvotes: 0