views:

467

answers:

2

Ok, I'm trying to add a "custom property" to a piece of text in a RichTextBox control. I thought it would be easy, but apparently not :-)

The basic functionality I want is to be able to set a property on a particular word and be able to detect, when a word is double clicked, if that property is there or not.

My intial approach was to create a new DP and apply it to the text, but TextRange isn't actually a DependencyObject and Reflector shows it only accepts certain DPs that it maps directly to "real" properties.

Unfortunately I can't seem to find any other "hook" to let me do this. I can't inherit from any of the things that I CAN apply to text, as everything I need is either sealed, or contains internal abstracts, so I'm at a bit of a loss.

I could just keep track of ranges that have the property externally, and update that as the text is updated, but that sounds pretty horrible, and I really don't want to have to create my own RichTextBox just for this one feature!

Any suggestions would be most welcome :-)

+1  A: 

Personal expierience with the RichTextBox learned me that this control might combine Run and Spans if they look alike, meaning you will loose the custom information you tried to set with a TextRange. This happened a lot with overlapping regions of TextRange. So basicly, you cannot use TextRange for this problem.

We had similar problems with this control, and we ended up with a little dirty hack actually. Here is what we ended up doing:

You can insert InlineUIContainer and BlockUIContainer elements into your FlowDocument. Inside one of those container, you can put any UIElement you wish.. We ended up creating an attached property, and place these gems of information inside Control controls which lived in those UIContainers.

If we ever needed the information, we looked up the nearest container element, extract the information, et voila... Its a drag.. I know, but it worked :)..

One problem though.. The user can manually remove these containers by hand, simply by pressing the delete button. You can however detect this with the Unloaded events which will be fired when this happens.

Arcturus
Excellent.. I was trying to find a similar "hack" that would let me "inject" something into the document, but hadn't managed to find anything. I'll have a look at InlineUIContainer and BlockUIContainer.. thanks!
Steven Robbins
A: 

InlineUIContainers will not be saved in a TextRange.Save call for XamlPackage though, even if preserveTextElements is true. I think you have to use XamlWriter to preserve InlineUIContainers, but then you lose the ability to embed images into the document.

I have yet to find a way to embed custom properties on pieces of the document AND be able to embed images.

Tim Gemma