在插入符号位置将文本插入 WPF 文本框
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2117259/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Insert text into WPF textbox at caret position
提问by Roice
How can I insert text into a WPF textbox at caret position? What am I missing? In Win32 you could use CEdit::ReplaceSel().
如何在插入符号位置将文本插入 WPF 文本框?我错过了什么?在 Win32 中,您可以使用 CEdit::ReplaceSel()。
It should work as if the Paste() command was invoked. But I want to avoid using the clipboard.
它应该像调用 Paste() 命令一样工作。但我想避免使用剪贴板。
回答by Tarsier
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);
回答by iyalovoi
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;
回答by Roice
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.
然后滚动到 Tarsier 所述的位置。
回答by Thorsten79
Use TextBox.CaretIndex to modify the text bound to the TextBox.Text property.
使用 TextBox.CaretIndex 修改绑定到 TextBox.Text 属性的文本。