WPF RichTextBox scroll to TextPointer

早过忘川 提交于 2019-12-23 09:52:08

问题


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?


回答1:


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();
}



回答2:


Use GetCharacterRect to get position of TextPointer in RichTextBox:

Rect r = textPointer.GetCharacterRect(LogicalDirection.Backward);
rtb.ScrollToVerticalOffset(r.Y);



回答3:


So if you're wondering why BringIntoView() isn't working or it scrolls to the top of your textbox, it's likely because you are attempting to "bring into view" the Inline that comprises your entire scrollable text content - it "brings to view" this inline, which starts at (you guessed it) the "start" TextPosition at the top.

Solution is to use ScrollToVerticalOffset() per Miroslav's answer.




回答4:


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.



来源:https://stackoverflow.com/questions/6908983/wpf-richtextbox-scroll-to-textpointer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!