如何通过在WPF中为每个段落隐藏代码来设置RichTextBox的滚动位置



我有一个丰富的文本框和一个包含多个段落的长文本。我想在后面写代码,以调整滚动条的垂直位置,使其专注于特定的段落。是否可以根据富文本框的大小和段落位置来计算垂直偏移?

RichTextBox.ScrollToVerticalOffset(calculatedData)

为了获得位置,最初,您应该在段落开头获得插入符号的位置。然后,得到边界框的矩形。矩形的Y属性可以滚动RichTextBox第一个位置的段落。

private void RichTextBox_OnLoaded(object sender, RoutedEventArgs e)
{
// Get the paragraph block text
var textBlock = RichTextBox.Document.Blocks.ElementAt(2);
//get the caret position of the start of the paragraph
var startOfTextBlock = textBlock.ContentStart;
// get the the character rectangle
Rect charRect = startOfTextBlock.GetCharacterRect(LogicalDirection.Forward);
// set the the vertical offset ot the Y position of the rectangle 
RichTextBox.ScrollToVerticalOffset(charRect.Y);
}

最新更新