Wpf – Determining the selected InlineUIContainer in a WPF RichTextBox

richtextboxselectionwpf

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">
        <FlowDocument>
            <Paragraph>
                <Run>Some text before</Run>
                <InlineUIContainer>
                    <Label>I am a label</Label>
                </InlineUIContainer>
                <Run>Some text after</Run>
            </Paragraph>
        </FlowDocument>
    </RichTextBox>

In the SelectionChanged event I have tried using;

rtf.CaretPosition.GetAdjacentElement(rtf.CaretPosition.LogicalDirection)

… 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);
Console.WriteLine(pointer.GetAdjacentElement(pointer.LogicalDirection));

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

Matt

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))
                        {
                            Console.WriteLine("YES");
                        }
                    }
                }
            }
        }