Jebarson's dev blog

Coffee, Code

Get text from RichTextBlockOverflow Control

RichTextBlockOverflow is one of my favorite control. As we all know, it allows you to render the overflown text from a RichTextBlock. Virtually you can render the overflow text to any number of level.

Below is how a the overflow happens when you got one RichTextBlock and two RichTextBlockOverflow to render the overflown text.

RichTextBlockOverflow Rendering Flow
RichTextBlockOverflow Rendering Flow

However, there is no straight way to read the text from the overflow control. And the reasons are,

  1. You never bind or assign a content to the overflow control but the RichTextBlock.
  2. The runtime will never know what content goes into this control unless a UI rendering happens.
  3. Resize or any repaint operation in the UI will affect the content which goes in here.

However, not everything is lost. The AutomationPeer comes as a savior here. And this information is hidden in the MSDN documentation under the remarks section of “RichTextBlockOverflowAutomationPeer

"GetName returns a plain-text representation of the RichTextBlockOverflow text content from Blocks.

Lets consider the below example.

<RichTextBlock x:Name="FirstCtl" Height="40" OverflowContentTarget="{Binding ElementName=OverflowCtl1}">
    <Paragraph>
        This is a test for the rich text block</Paragraph>
    <Paragraph>to see how the overflow works in this control and</Paragraph>
    <Paragraph>also how the second level of overflow works.
    </Paragraph>
</RichTextBlock>
<RichTextBlockOverflow Height="40" x:Name="OverflowCtl1" OverflowContentTarget="{Binding ElementName=SecondCtl}" />
<RichTextBlockOverflow x:Name="SecondCtl" Height="30" />

After rendering the UI of the above XAML into a narrow window, below is how the visual tree will look like.

RichTextBlockOverflow Visual Tree
RichTextBlockOverflow Visual Tree

Now that the AutomationPeer is exposing the text content into the name as mentioned in the documentation, its just a matter of getting it.

Debug.Write(FrameworkElementAutomationPeer.FromElement(this.OverflowCtl1).GetName());

It saved my day and hope it saves your’ s too.

Get text from RichTextBlockOverflow Control

Leave a Reply

Scroll to top