为什么 RichTextBox 隐式添加换行符? [英] Why does RichTextBox implicitly add newline?

查看:62
本文介绍了为什么 RichTextBox 隐式添加换行符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有从 RichTextBox 派生的 Foo 类,它有私有方法 add_text,我发现它给出了错误的结果.例如,它给出了 x\r\n,而不是添加文本 x.RichTextBox 类的问题是什么?在使用 add_text 方法之前,我用 Document.Blocks.Clear() 命令清除了内容

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 命令给出相同的结果(添加了 \r\n 个字符)

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

推荐答案

这是因为 RTB 的对象模型仅支持段落中的文本(称为块).它会自动创建一个并将您的文本放入其中.

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.

这篇关于为什么 RichTextBox 隐式添加换行符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆