Defining the selected InlineUIContainer in WPF RichTextBox

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

I currently have a RichTextBox as shown below:

    <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 tried to use;

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

... which returns null.

I can do this 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 would really like it to work when the position of the RichTextBox carriage changes.

Is there any way to achieve this?

Thank you in advance

Matt

+3
source share
2 answers

If an x: Name attribute is assigned to your InlineUIContainer, you can find it using this code:

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

:

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");
                        }
                    }
                }
            }
        }
+7

CaretPosition.Parent "is".

+1

All Articles