简体   繁体   English

WPF RichTextBox 滚动到 TextPointer

[英]WPF RichTextBox scroll to TextPointer

The WPF RichtTextBox has a method to scroll: WPF RichtTextBox 有一个滚动方法:

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?如何以有意义的方式将 TextPointer 转换为 double?

Have a look at the FrameworkElement.BringIntoView Method.看看 FrameworkElement.BringIntoView 方法。 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();
}

Use GetCharacterRect to get position of TextPointer in RichTextBox:使用 GetCharacterRect 获取 TextPointer 在 RichTextBox 中的位置:

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

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:这是一个将 RichTextBox 文本指针滚动到视图中心的示例:

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.您不需要检查负数,因为滚动说明了这一点。

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.因此,如果您想知道为什么BringIntoView()不起作用或它滚动到文本框的顶部,很可能是因为您试图“显示”包含整个可滚动文本内容的Inline - 它“显示”查看”这个内联,它开始于(你猜对了)顶部的“开始” TextPosition

Solution is to use ScrollToVerticalOffset() per Miroslav's answer .解决方案是根据Miroslav's answer使用ScrollToVerticalOffset()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM