如何通过 WPF 中的代码为每个段落设置 RichTextBox 的滚动位置?
How to set the scroll position of a RichTextBox by behind code in WPF for every paragraph?
我有一个富文本框和一个包含多个段落的长文本。我想写后面的代码来调整滚动条的垂直位置以专注于特定段落。是否可以根据富文本框的大小和段落位置来计算垂直偏移量?
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);
}
我有一个富文本框和一个包含多个段落的长文本。我想写后面的代码来调整滚动条的垂直位置以专注于特定段落。是否可以根据富文本框的大小和段落位置来计算垂直偏移量?
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);
}