R – How to find the viewable area of a WPF RichTextBox

netrichtextboxwpf

I'm working on an app where I have a bunch of text in a RichTextBox. I'm jumping to various positions within the text, (hopping to an arbitrary paragraph for example) which seems to work by send the caret to that position but I can't seem to control where in the viewable area the caret ends up.

Sometimes the caret ends up at the top of the RichTextBox and sometimes at the bottom. This would be fine if I was only interested in the line that the caret is on but I'm interested in the entire paragraph.Ideally I'd like to get the caret in the middle of the RichTextBox everytime. Unless the Paragraph is longer than the viewable area.

My question. Is there a way to determine the viewable area of a RichTextBox and so do a calculation on how to position the caret properly? If I had that value I can then decided whether to put the caret in the middle (and know where the middle is) or at the top. Thanks for you help.

Best Answer

I solved this problem. A RichTextBox has a VerticalOffset property which when added to the position of the textpointer will give you the actual offset.

Using the offset you can use RichTextBox.ScrollToVerticalOffset to scroll the box based on the RichTextBox.ActualHeight property.

an example: assume I have a TextPoint pointer1 at the position I want to scroll to

Rect thisposition = pointer1.GetCharacterRect(LogicalDirection.Forward);

richTextBox1.Focus();
richTextBox1.CaretPosition = pointer1;


double totaloffset = thisposition.Top + richTextBox1.VerticalOffset;
richTextBox1.ScrollToVerticalOffset(totaloffset - richTextBox1.ActualHeight / 2);