0

I have a rich textbox and a long text with several paragraphs. I want to write behind codes to adjust the vertical position of the scroll bar to focus on a specific paragraph. Is it possible to calculate the vertical offset based on the size of the rich textbox and paragraph position?

RichTextBox.ScrollToVerticalOffset(calculatedData)
Pavel Anikhouski
  • 21,776
  • 12
  • 51
  • 66
icn
  • 1,783
  • 2
  • 7
  • 13

1 Answers1

3

In order to obtain the position, initially, you should get the position of caret at the start of the paragraph. Then, you get the rectangle of bounding box. The Y property of the rectangle can scroll the paragraph at the first of the 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);
        }
Pavel Anikhouski
  • 21,776
  • 12
  • 51
  • 66