将FlowDocument类型序列化为二进制文件-WPF

问题描述

如何序列化FlowDocument类型并将其另存为二进制文件?我是WPF的新手,正尝试序列化一个具有FlowDocument的对象,该对象的值我想从RichTextBox控件中获取一个示例类就是这样-

[Serializable]
public class MenuAnalysisDTO

{
    public FlowDocument Item { get; set; }

    public FlowDocument Deduction { get; set; }

}

我使用“ BinaryFormatter”进行序列化并得到了一个错误,因为-'类型'System.Windows.Documents.FlowDocument'em.Windows.Documents.FlowDocument'未标记为可序列化。'

解决方法

作为Clemens提供的链接的替代方法,您可以使用FlowDocument的内置功能:

private FlowDocument SaveAndLoadRtfDocumentExample(FlowDocument document)
{ 
  // Save 

  // Convert the FlowDocument to RTF formatted file
  var documentRange = new TextRange(document.ContentStart,document.ContentEnd);

  using (var outputStream = new FileStream("[Destination_File_Path]",File.OpenOrCreate))
  {
    documentRange.Save(outputStream,DataFormats.Rtf);
  }

  // Load

  // Convert the RTF formatted file stream to a FlowDocument     
  var blankDocument = new FlowDocument();
  var blankDocumentRange = new TextRange(blankDocument.ContentStart,blankDocument.ContentEnd);

  using (var inputStream = new FileStream("[Source_File_Path]",File.Open))
  {
    blankDocumentRange.Load(inputStream,DataFormats.Rtf);
    return blankDocument;
  }
}

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...