1

I have class Foo derived from RichTextBox, which has private method add_text and I came across that it gives wrong results. For examples, instead of added text x it gives x\r\n. What is the problem of RichTextBox class? before usage of add_text method I cleared content with Document.Blocks.Clear() command

// Appends text to the end with specified selection colors
private void add_text(string text, Brush foreground_brush, Brush background_brush)
{
    // here new TextRange(Document.ContentStart, Document.ContentEnd).Text gives ""

    TextRange text_range = new TextRange(Document.ContentEnd, Document.ContentEnd);
    text_range.Text = text;
    // Here new TextRange(Document.ContentStart, Document.ContentEnd).Text gives "x\r\n"

    text_range.ApplyPropertyValue(TextElement.BackgroundProperty, background_brush);
    text_range.ApplyPropertyValue(TextElement.ForegroundProperty, foreground_brush);
}

UPD: AppendText command gives the same result (\r\n characters were added)

Alex Aparin
  • 4,393
  • 5
  • 25
  • 51

1 Answers1

2

This is because the RTB's object model only supports text in paragraphs (known as Blocks). It creates one automatically and puts your text in it.

We had to strip all the trailing newlines from our text, otherwise each time it was loaded and saved we'd get another.

Robin Bennett
  • 3,192
  • 1
  • 8
  • 18
  • Is there any documentation reference for such behaviour? It seems very weird for me, I thought that paragraphs will contain any text without modifications – Alex Aparin Jun 21 '19 at 15:07
  • I didn't find any. It's not that it's modifying your text, but that you're adding text to the default paragraph, and then when you read back the whole document (including that paragraph) it renders its object model as a string, with a line break at the end of each paragraph. – Robin Bennett Jun 21 '19 at 15:16