简体   繁体   中英

Scroll to Position in RichTextBox

I need help in scrolling to highlighted text/string positions in a rich text box. I was able to find text and highlight it but I want the user to be able to click on a Next button and that event to scroll to the vertical offset position of the first occurrence of the highlighted word to the next and so on after each click. Any help specifically with finding the position for the vertical offset of the line of the highlighted text would be helpful as well. Thanks in advance.

I found an answer to a similar question here . Below is the code that I believe will do the trick for you.

TextPointer start = txtEditor.Selection.Start;
FrameworkContentElement fce = (start.Parent as FrameworkContentElement);
if (fce != null)
{
    fce.BringIntoView();
}

I had two TextPointer s with which I created a TextRange , then used .ApplyPropertyValue on that to set background colour. Then I tried...

var fce = fromTextPointer as FrameworkContentElement;
if (fce != null)
    fce.BringIntoView();   // unreliable

...but it was unreliable. What I eventually discovered worked - ostensibly reliably - was using the .Start of the TextRange I created from the same fromTextPointer :

var fce = textRange.Start.Parent as FrameworkContentElement;
if (fce != null)
    fce.BringIntoView();    // ostensibly reliable

I would guess that certain actions - possibly the creation of a TextRange but more likely invocation of .ApplyPropertyValue - trigger enough position normalisation within the widget and/or textRange object that the .BringIntoView() is then reliable.

Perhaps this isn't necessary for the Selection - as in Ward s answer - but I wasn't manipulating the Selection and this question doesn't mention the Selection specifically either, so posting here in-case it helps some other poor soul avoid hours of WPF "fun".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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