gpt4 book ai didi

c# - 从 TextBlock 以 RTF 格式保存文本时,WPF 新行不起作用

转载 作者:行者123 更新时间:2023-11-30 22:01:36 24 4
gpt4 key购买 nike

我在 WPF 中使用 TextBlock 来显示格式化文本。显示效果很好,但是当我尝试将内容保存到 RTF 格式的文件时,未使用换行符。我收到“一行文本”。

我使用这样的代码行:

displayBuffer.Inlines.Add(new Run("Blabla \n") 
{ TextDecorations = TextDecorations.Underline, Foreground = Brushes.Blue });

并保存:

        FileStream fileStream = new FileStream(dlg.FileName, FileMode.Create);
TextRange range = new TextRange(displayBuffer.ContentStart, displayBuffer.ContentEnd);
range.Save(fileStream, DataFormats.Rtf);

我已尝试\n\r\n 和 Environment.NewLine 作为行尾,但没有成功。知道我做错了什么吗?

编辑:发布过程字符串以获得正确结果的非常有趣的想法(Stefano 引用)。我在这里查看了 RTF 格式 http://latex2rtf.sourceforge.net/rtfspec_7.html#rtfspec_18和\par 可能是我想要的,但\line 没问题。

奇怪的是 Range.Save 生成​​的 RTF 文件根本不包含\line 或\par ?因此,我可以按照您的引用资料中所述,用特殊字符序列替换\n,并用\par 替换 RTF 文件中的这个字符。

但是我更愿意在保存文件之前执行此操作。有没有办法做 range.Save(fileStream, DataFormats.Rtf) 的等价物来将字符串保存在内存中?否则,我将需要编写一个临时文件来处理它并重写最后一个,但是对于本应简单的东西来说,所有这些看起来都很丑陋?

最佳答案

以下代码实现了一个方法,该方法将 RichTextBox 作为参数,并返回表示 RichTextBox 纯文本内容的字符串。该方法根据 RichTextBox 的内容创建一个新的 TextRange,使用 ContentStart 和 ContentEnd 指示要提取的内容范围。 ContentStart 和 ContentEnd 属性各自返回一个 TextPointer,并且可在表示 RichTextBox 内容的基础 FlowDocument 上访问。 TextRange 提供了一个 Text 属性,它以字符串形式返回 TextRange 的纯文本部分。

试试这个:

string StringFromRichTextBox(RichTextBox rtb)
{
TextRange textRange = new TextRange(
// TextPointer to the start of content in the RichTextBox.
rtb.Document.ContentStart,
// TextPointer to the end of content in the RichTextBox.
rtb.Document.ContentEnd
);

// The Text property on a TextRange object returns a string
// representing the plain text content of the TextRange.
return textRange.Text;
}

要正确保存为 rtf 格式,试试这个:

using (FileStream file = new FileStream(fileLocation, FileMode.Create))
{
textrange.Save(file, System.Windows.DataFormats.Rtf);
}

关于c# - 从 TextBlock 以 RTF 格式保存文本时,WPF 新行不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27569449/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com