0

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.

Sheridan
  • 68,826
  • 24
  • 143
  • 183
Skilla89
  • 45
  • 2
  • 6
  • I don't use the `RichTextBox` personally, so I can't help from my experience. I did a quick search for you and found some pages on the internet that could help you, you may need to extract a bit of knowledge from each article to build up your functionality, so please don't expect a complete solution. http://msdn.microsoft.com/en-us/library/system.windows.controls.richtextbox.caretposition%28v=vs.110%29.aspx, http://stackoverflow.com/questions/1827323/c-synchronize-scroll-position-of-two-richtextboxes, http://www.codeproject.com/Articles/7830/Scrolling-Around-with-the-RichTextBox-Control – Sheridan Jan 10 '14 at 10:52

2 Answers2

3

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();
}
Community
  • 1
  • 1
Ward
  • 116
  • 1
  • 9
1

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".

Tony Delroy
  • 102,968
  • 15
  • 177
  • 252