您可以使用GetOffsetToPosition()
和GetPositionAtOffset()
來保存插入符的相對位置並恢復它。
換句話說,假設RichTextBox的初始化是這樣的:
RichTextBox rtb;
int paragraphIndex = -1;
int indexInParagraph;
public MainWindow()
{
InitializeComponent();
rtb = new RichTextBox();
rtb.Document = new FlowDocument();
Paragraph para = new Paragraph(new Run("some text some text some text."));
rtb.Document.Blocks.Add(para);
// sets the caret at a specific (random) position in the paragraph:
rtb.CaretPosition = para.ContentStart.GetPositionAtOffset(5);
this.Content = rtb;
}
注意班上三個私有字段。
您應該保存插入符號的段落指數和尖指數段落,你替換文本之前:
public void SaveCaretState()
{
//enumerate and get the paragraph index
paragraphIndex = -1;
foreach (var p in rtb.Document.Blocks)
{
paragraphIndex++;
if (p == rtb.CaretPosition.Paragraph)
break;
}
//get index relative to the start of the paragraph:
indexInParagraph = rtb.CaretPosition.Paragraph.ElementStart.GetOffsetToPosition(rtb.CaretPosition);
}
,只要你喜歡恢復它:
public void RestoreCaretState(MouseEventArgs e)
{
// you might need to insure some conditions here (paragraph should exist and ...)
Paragraph para = rtb.Document.Blocks.ElementAt(paragraphIndex) as Paragraph;
rtb.CaretPosition = para.ElementStart.GetPositionAtOffset(indexInParagraph);
}
請注意,它是一個簡單的例子,RichTextBox.Document
中可能有其他Block
。然而,這個想法和實施並沒有太大的不同。
來源
2017-03-06 01:14:41
Ron
謝謝你的幫助。我注意到一個位置將一個塊視爲一個位置,因此當我添加塊時,+ =的位置可以跳過整個塊,但是我可以計算出該位置。謝謝你的幫助。 – user6590430