简体   繁体   English

如何通过 WPF 中的代码为每个段落设置 RichTextBox 的滚动 position?

[英]How to set the scroll position of a RichTextBox by behind code in WPF for every paragraph?

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.我想在后面写代码来调整滚动条的垂直 position 以专注于特定段落。 Is it possible to calculate the vertical offset based on the size of the rich textbox and paragraph position?是否可以根据富文本框的大小和段落 position 计算垂直偏移量?

RichTextBox.ScrollToVerticalOffset(calculatedData)

In order to obtain the position, initially, you should get the position of caret at the start of the paragraph.为了获得 position,最初,您应该在段落开头获得插入符号的 position。 Then, you get the rectangle of bounding box.然后,你得到边界框的矩形。 The Y property of the rectangle can scroll the paragraph at the first of the RichTextBox.矩形的 Y 属性可以滚动 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);
        }

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

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