Scroll to Position in RichTextBox

2019-08-29 11:30发布

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.

2条回答
Lonely孤独者°
2楼-- · 2019-08-29 11:53

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();
}
查看更多
▲ chillily
3楼-- · 2019-08-29 12:11

I had two TextPointers 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 Wards 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".

查看更多
登录 后发表回答