将RichTextBox的文本设置为字符串T后,RichTextBox中的插入符位置会“丢失”(跳到了开头)。以下是我尝试在其“丢失”后“恢复”它的方法:
public static int GetCaretIndex(RichTextBox C)
{
return new TextRange(C.Document.ContentStart, C.CaretPosition).Text.Length;
}
...
int CaretIndex = GetCaretIndex(C); // Get the Caret position before setting the text of the RichTextBox
new TextRange(C.Document.ContentStart, C.Document.ContentEnd).Text = T; // Set the text of the RichTextBox
C.CaretPosition = C.Document.ContentStart.GetPositionAtOffset(CaretIndex, LogicalDirection.Forward); // Set the Caret Position based on the "Caret Index" variable
然而,这段代码并没有起作用。 "恢复"的插入符号位置与"原始"位置不同(由于某种原因始终在"原始"位置之后)。
将RichTextBox的CaretPosition保存为TextPointer似乎也不起作用。
有人能提供另一种“恢复”插入符号的方法,或者修复上面的代码吗?