3

我正在使用XamlWriter.SaveandXamlReader.Load将 FlowDocument 序列化和反序列化为字节数组以存储它:

private static byte[] FlowDocumentToByteArray(FlowDocument flowDocument)
{
    using (var stream = new MemoryStream())
    {
        XamlWriter.Save(flowDocument, stream);
        stream.Position = 0;
        return stream.ToArray();
    }
}

private static FlowDocument FlowDocumentFromByteArray(byte[] bytes)
{
    using (var stream = new MemoryStream(bytes))
    {
        return (FlowDocument)XamlReader.Load(stream);
    }
}

但是我在保留空白时遇到了麻烦。以下测试失败:

[TestMethod]
public void FlowDocumentTabsNoBackground()
{
    var flowDocument = new FlowDocument();

    var paragraph = new Paragraph();
    paragraph.Inlines.Add(new Run("\t"));
    paragraph.Inlines.Add(new Run("a"));
    flowDocument.Blocks.Add(paragraph);

    byte[] bytes = FlowDocumentToByteArray(flowDocument);

    FlowDocument flowDocumentOut = FlowDocumentFromByteArray(bytes);

    var textRange = new TextRange(flowDocumentOut.ContentStart, 
        flowDocumentOut.ContentEnd);
    Assert.IsTrue(textRange.Text.StartsWith("\t"));
}

但是这个测试通过了:

[TestMethod]
public void FlowDocumentTabsWithBackground()
{
    var flowDocument = new FlowDocument();

    var paragraph = new Paragraph();
    paragraph.Inlines.Add(new Run("\t"));
    paragraph.Inlines.Add(new Run("a")
        {
            Background = new SolidColorBrush(Color.FromArgb(255, 255, 255, 255))
        }
    );
    flowDocument.Blocks.Add(paragraph);

    byte[] bytes = FlowDocumentToByteArray(flowDocument);

    FlowDocument flowDocumentOut = FlowDocumentFromByteArray(bytes);

    var textRange = new TextRange(flowDocumentOut.ContentStart, 
        flowDocumentOut.ContentEnd);
    Assert.IsTrue(textRange.Text.StartsWith("\t"));
}

为什么选项卡不能通过序列化/反序列化循环,为什么在段落中的其中一个运行中添加背景颜色有帮助?

4

0 回答 0