tags:

views:

940

answers:

4

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.

A: 

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

Thorsten79
Isn't there something more simple? And what if text is already selected? How can it be replaced by the new text? And how can I make that the caret scrolls into view?
Roice
Actually this IS a very simple way.
Thorsten79
But you did not consider my other needs:How can it be replaced by the new text? And how can I make that the caret scrolls into view?
Roice
Tarsier has answered all that.
Thorsten79
+3  A: 

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
+1  A: 

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
TextBox does not have a SelectedIndex property. I assume you meant SelectedText, and, yes, you're right, it is simpler.
Tarsier
Yes, I did mean SelectedText. I changed it in my answer above.
Roice
A: 

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