如何将WPF RichTextBox带格式文本保存到JSON以实现后续恢复
实现方案
WPF 中 RichTextBox 的内容载体是 FlowDocument,你可以通过将 FlowDocument 转换为可序列化的格式来保留全量样式,以下是两种可落地的方案:
方案一:转换为 XAML 字符串(推荐,成本最低)
FlowDocument 本身支持 XAML 序列化,该方案可以100%还原所有内置样式,不需要手动解析样式属性,也不会出现循环引用问题。
序列化代码
using System.Windows.Markup; using System.IO; // 将RichTextBox内容转为XAML字符串 public string SerializeRichTextBox(RichTextBox rtb) { using (var stringWriter = new StringWriter()) { XamlWriter.Save(rtb.Document, stringWriter); return stringWriter.ToString(); } }
拿到的XAML字符串可以直接作为普通字段存入对象,或者序列化到JSON文件中。
反序列化还原代码
using System.Windows.Markup; using System.IO; using System.Xml; // 将XAML字符串还原到RichTextBox public void DeserializeRichTextBox(RichTextBox rtb, string xamlContent) { using (var stringReader = new StringReader(xamlContent)) using (var xmlReader = XmlReader.Create(stringReader)) { rtb.Document = (FlowDocument)XamlReader.Load(xmlReader); } }
方案二:自定义结构序列化(适合需要手动控制格式的场景)
如果你不想存储XAML字符串,可以遍历FlowDocument的内容节点,提取样式属性存入自定义可序列化类,再序列化到JSON。
首先定义可序列化类
// 自定义富文本根结构 public class CustomRichText { public List<CustomParagraph> Paragraphs { get; set; } = new(); } // 段落结构 public class CustomParagraph { public List<CustomTextRun> Runs { get; set; } = new(); } // 文本片段+样式结构 public class CustomTextRun { public string Text { get; set; } public string FontColorHex { get; set; } public double FontSize { get; set; } public bool IsBold { get; set; } public bool IsUnderline { get; set; } // 可按需扩展字体、斜体、背景色等其他属性 }
转换逻辑
遍历FlowDocument的所有Block和Inline节点,把每个Run的属性赋值到自定义类即可,后续可以直接将自定义类序列化到JSON,还原时反向转换为FlowDocument即可。
注意事项
- WinForm 中的
RichTextBox.SaveFile()方法在WPF中不存在,不要混淆两个框架的控件API - 不要直接序列化
FlowDocument或RichTextBox实例,内部包含大量UI关联的引用对象,必然会触发循环引用报错
内容的提问来源于stack exchange,提问作者thecoureurdu23
相关产品推荐
相关产品推荐

