Insert text into WPF textbox at caret position

2019-02-05 20:24发布

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.

标签: wpf textbox
4条回答
老娘就宠你
2楼-- · 2019-02-05 20:55

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

查看更多
冷血范
3楼-- · 2019-02-05 20:57

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;
查看更多
Emotional °昔
4楼-- · 2019-02-05 21:16

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);
查看更多
家丑人穷心不美
5楼-- · 2019-02-05 21:16

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.

查看更多
登录 后发表回答