Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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">
        <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

like image 341
user77159 Avatar asked Mar 01 '23 22:03

user77159


1 Answers

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");
                        }
                    }
                }
            }
        }
like image 84
witters Avatar answered Mar 04 '23 11:03

witters