Wpf – Determining the selected InlineUIContainer in a WPF RichTextBox


I'd like to determine if there is an InlineUIContainer (or BlockUIContainer) at the current Caret position in a WPF RichTextBox.

Currently I have a RichTextBox as follows;

    <RichTextBox SelectionChanged="RichTextBox_SelectionChanged">
                <Run>Some text before</Run>
                    <Label>I am a label</Label>
                <Run>Some text after</Run>

In the SelectionChanged event I have tried using;


… which returns null.

I can do it using the MouseDoubleClicked event handler as follows;

Point pos = e.GetPosition(rtf);
TextPointer pointer = rtf.GetPositionFromPoint(pos, false);

But I'd really like to get it working when the RichTextBox caret position changes.

Is there any way I can achieve this?

Thanks in advance


Best Solution

If your InlineUIContainer is given a x:Name attribute, you can look for it specifically using this code:

if (rtf.Selection.Contains(myInlineUIContainer.ContentStart))

For more dynamic discovery you would need a loop something like this:

foreach (Block block in rtf.Document.Blocks)
            Paragraph p = block as Paragraph;
            if (p != null)
                foreach (Inline inline in p.Inlines)
                    InlineUIContainer iuic = inline as InlineUIContainer;
                    if (iuic != null)
                        if (rtf.Selection.Contains(iuic.ContentStart))