Scroll to Position in RichTextBox

时光怂恿深爱的人放手 提交于 2019-12-12 01:06:35

问题


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.


回答1:


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();
}



回答2:


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



来源:https://stackoverflow.com/questions/21032174/scroll-to-position-in-richtextbox

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!