Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert text into WPF textbox at caret position

Tags:

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.

like image 361
Roice Avatar asked Jan 22 '10 12:01

Roice


1 Answers

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); 
like image 152
Tarsier Avatar answered Sep 24 '22 03:09

Tarsier