I’ve created a highlighting mechanism for a RichTextBox in Silverlight 4. It’ll get character positions and draw rectangle(s) over the text.
The trouble I have now is with scrolling on the RichTextBox. As I scroll all of my precious highlighting gets left behind. Is there any way I can add an event handler to a scroll event and/or a scrolling position of the RichTextBox? Or is there some better way in which I can link the position of the highlighting rectangles to the RichTextBox?
The trick would be to get what ever panel (I guess its a Canvas?) that you are overlaying the RichTextBox with to actually exist within the same
ScrollViewerthat rich text exists in.The following is very rough idea but should get you on the path to reasonable solution.
You can do this using a custom style for the
RichTextBox. The default style for this control can be found here.Copy this style into a resource in your containing UserControl and point your
RichTextBoxStyleproperty at it. So far nothing is different but now you can play about with the template. The relevant portion currently looks like this:-Now we can tweak it like this:-
You’ll note that we’ve moved the name “ContentElement” from the
ScrollViewerto the newContentControl. Having aFrameworkElementcalled “ContentElement” is the only feature that the RichTextBox stipulates about its template.Now overlaying this
ContentControlwe can place aCanvaswhere you can place your highlighting rectangles. If the user scrolls thisRichTextBoxthe wholeGridcontaining both the Content and the Highlights will scroll together.The only remaining trick is acquiring the “HighlightOverlay” so that you can add your rectangle to it. Here is some code that will grab it:-
You will be wondering where the
Descendentsmethod is coming from, it is here.