WPF RichTextBox automatically merges two adjacent Runs

896 Views Asked by At

I have a RichTextBox containing two Runs:

<RichTextBox>
    <RichTextBox.Document>
        <FlowDocument>
            <FlowDocument.Blocks>
                <Paragraph Name="par">
                    <Run Text="First"/>
                    <Run Text="Second"/>
                </Paragraph>
            </FlowDocument.Blocks>
        </FlowDocument>
    </RichTextBox.Document>
</RichTextBox>

When I iterate through the Inlines of the par, I see three Runs: "First", " "(space) and "Second". It's ok. But if I delete second " " Run (using Backspace key, for example) and then iterate through the Inlines of the par, I see only one "FirstSecond" Run. RichTextBox merges two remaining Runs into single Run. However, if "First" and "Second" Runs have different TextFont or TextWeight values, RichTextBox won't merge them and I'll see two distinct Runs: "First" and "Second".

Now my question: How can I preserve adjacent Runs from being merged automatically by RichTextBox?

I would like to get the behaviour similar to the one when Runs have different TextFont or TextWeight values, but visually their formats should be equal. I've tried to set different Tag values for the different Runs, but it didn't help. Maybe, there is some "logical" format, that doesn't influence the appearance of the Runs, but warns RichTextBox to distinguish them.

1

There are 1 best solutions below

2
On

Though I haven't found a clear solution, there is a workaround. Run has the Typography property, which, in its turn, has the Int32 AnnotationAlternates property. This property defines the fine tuning of the outlook for the specific characters of the specific fonts. If this property isn't used as intended, it can be used as a "logical" format for a Run. As written in MSDN:

If the value of AnnotationAlternates is greater than zero and the selected font does not support annotation alternates, the default form of the letter is displayed.

In my application I use Segoe UI font, which, as it turns out, doesn't support annotation alternates, so this workaround works for me. If you use font that supports annotation alternates, you can try to use rather big values of the AnnotationAlternates property, maybe, it won't influence the appearance of the text.