问题
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)
回答1:
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.
来源:https://stackoverflow.com/questions/56705725/why-does-richtextbox-implicitly-add-newline