Search code examples
wpfrichtextboxflowdocument

How to keep Run together after modification in WPF RichTextBox


I have the following Paragraph created by code in a RichTextBox:

Paragraph paragraph = new Paragraph(new Run("text1"));
paragraph.Inlines.Add(new Run("   TEST   "));

This is how it looks in the XAML:

<Paragraph><Run>text1</Run><Run>   TEST   </Run></Paragraph>

When I modify the text inside the RichTextBox by typing, it creates a new Run instead of modifying the current one.

This is how the XAML looks like:

<Paragraph><Run>text1</Run><Run>   TE</Run><Run xml:lang="en-us"> </Run><Run>ST   </Run></Paragraph>

Can I somehow set the behavior to keep together and modify the current Run?


Solution

  • Obviously you can keep them together, you just have to set the language property of the Run:

    Run run = new Run("   TEST   ") {  Language = XmlLanguage.GetLanguage("en-us") };
    paragraph.Inlines.Add(run);
    

    Very intuitive, I should say….

    By using this, the actual run is modified instead of being splitted to pieces.