views:

68

answers:

1

This is a slightly abstract question, for which I apologize. I am not necessarily looking for a specific tested solution, but rather some suggestions that I can experiment with to find the one that works the best. All suggestions are welcome - the more varied and creative the better.

Here's the problem:

I have a Silverlight TextBlock that contains a paragraph of wrapping text. It may contain multiple runs with a variety of formatting applied, including multiple font sizes. It may be aligned left, right, center or justified and may contain runs that use right-to-left textflow. I need to be able to detect the character under the mouse pointer. In WPF I could solve this problem easily using the GetPositionFromPoint method, but since this method does not exist in Silverlight, I need a creative workaround.

One approach I have tried, with reasonable success, is to break the text into individual words and create a TextBlock for each of them. By rendering them in a WrapPanel I can identify the start position of each word and thus narrow the hit test zone. Finding the actual target character is then a matter of building the target word, character by character, until its width meets the mouse position.

Although my experimental technique works, it has two drawbacks. The first is performance, since it is expensive to render a large number of individual TextBlock instances in a WrapPanel. The second concern is that my line-breaking algorithm (crudely based on spaces and hyphens) may not exactly match that used by the real TextBlock used in the UI. Having just read the Unicode Line Breaking Algorithm, I realize that this is a whole subject in its own right. I do not want to risk a design that breaks under certain paragraph content conditions

I would ideally like to find a technique that allows me to to measure directly against the main TextBlock, but I welcome any innovative suggestions, no matter how bizarre they may appear.

Many thanks, Tim

+2  A: 

Use a RichTextBox instead, that does have a GetPositionFromPoint method.

AnthonyWJones
Thanks - I have accepted your answer. It is counter-intuitive to use such a heavyweight control for such a lightweight operation but, as I am increasingly discovering, Silverlight sometimes forces us to adopt unwelcome workarounds.
Tim Coulter
@Tim: "Forces" ... "Unwelcome". Lightweight = Less Features. If you want more features you need something with greater weight. Silverlight is all about compromise between overall download size and features.
AnthonyWJones