我正在编写一个扩展程序,允许用户将多个笔记合并到一个笔记中,并提供一些功能,例如在原始笔记的末尾添加句点。我正在编写将一个流文档的各个部分复制到另一个文档的代码,并插入句点。
我在将列表复制到新文档时遇到问题。出于某种原因,第一个listitem总是在Preceeding列表而不是列表中的段落中结束。
我的代码:
foreach (Block b in tempDoc.Blocks)
{
thisBlock++;
if (b is List)
{
pkhCommon.WPF.Helpers.AddBlock(b, mergedDocument);
}
else
{
Paragraph p = b as Paragraph;
foreach (Inline inl in p.Inlines)
{
if (!(inl is LineBreak))
pkhCommon.WPF.Helpers.AddInline(inl, mergedDocument);
}
if (thisElement != lastElement || thisBlock != lastBlock)
if ((bool)cb_AddPeriods.IsChecked)
pkhCommon.WPF.Helpers.AddInline(new Run(". "), mergedDocument);
else
pkhCommon.WPF.Helpers.AddInline(new Run(" "), mergedDocument);
}
}
以下是合并块的功能。 AddIline函数的工作方式相同。
public static void AddBlock(Block from, FlowDocument to)
{
if (from != null)
{
using (System.IO.MemoryStream stream = new System.IO.MemoryStream())
{
TextRange range = new TextRange(from.ContentStart, from.ContentEnd);
System.Windows.Markup.XamlWriter.Save(range, stream);
range.Save(stream, DataFormats.XamlPackage);
TextRange textRange2 = new TextRange(to.ContentEnd, to.ContentEnd);
textRange2.Load(stream, DataFormats.XamlPackage);
}
}
}
我无法理解为什么flowdocument决定将listitem放入PREceeding段落。
答案 0 :(得分:0)
Adding a block to the FlowDocument's block collection should put it at the end.
This works for for me.
Document.Blocks.Add(blockToAdd);
You are doing the save/load to clone the block right? Can you just try adding it this way at the end instead of inserting in the text range?
var blockToAdd = XamlReader.Load(stream) as Block;
Document.Blocks.Add(blockToAdd);
Part of your issue is that after saving, the stream position is at the end of the stream, so there is nothing to Load. There is probably a better way to fix this but I am out of time to help. Setting position to 0 feels wrong. This has no parse exception.
var from = new System.Windows.Documents.List(new ListItem(new Paragraph(new Run("Blah"))));
using (var stream = new MemoryStream())
{
System.Windows.Markup.XamlWriter.Save(from, stream);
stream.Position = 0;
Block b = System.Windows.Markup.XamlReader.Load(stream) as Block;
}