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
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");
}
}
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With