Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF RichTextBox scroll to TextPointer

The WPF RichtTextBox has a method to scroll:

RichTextBox.ScrollToVerticalOffset(double)

I want to scroll in such a way, that a certain range or at least the start of it comes into view. How can I convert a TextPointer to double in a meaningful way?

like image 645
B_old Avatar asked Aug 02 '11 08:08

B_old


2 Answers

Have a look at the FrameworkElement.BringIntoView Method. I'm using something like this:

public void Foo(FlowDocumentScrollViewer viewer) {
    TextPointer t = viewer.Selection.Start;
    FrameworkContentElement e = t.Parent as FrameworkContentElement;
    if (e != null)
         e.BringIntoView();
}
like image 69
Zak Avatar answered Oct 06 '22 17:10

Zak


I'm somewhat late, but here is a more complete answer. The current scroll offsets need to be combined with the character position. Here is an example that scrolls RichTextBox text pointer to the center of the view:

var characterRect = textPointer.GetCharacterRect(LogicalDirection.Forward);
RichTextBox.ScrollToHorizontalOffset(RichTextBox.HorizontalOffset + characterRect.Left - RichTextBox.ActualWidth / 2d);
RichTextBox.ScrollToVerticalOffset(RichTextBox.VerticalOffset + characterRect.Top - RichTextBox.ActualHeight / 2d);

You don't need to check for negative numbers, as the scrolling accounts for this.

like image 39
username Avatar answered Oct 06 '22 18:10

username