Copying one FlowDocument to Second FlowDocument

為{幸葍}努か 提交于 2019-12-04 21:56:27

问题


How can i copy the contents of one FlowDocument to another FlowDocument below is what i tryed

foreach (var blk in fd1.Blocks)
{
   fd2.Blocks.Add(blk);
}

fd1 is FlowDocument1 and fd2 is FlowDocument2.

But i get the below error.

Collection was modified; enumeration operation may not execute.

Thanks

Arvind


回答1:


Because each Block is 'owned' by a FlowDocument, it cannot just be added to another. You must serialize it and then deserialize it, which breaks the bond with the original FlowDocument, which allows you to add it to another.

/// <summary>
/// Adds one flowdocument to another.
/// </summary>
/// <param name="from">From.</param>
/// <param name="to">To.</param>
public static void AddDocument(FlowDocument from, FlowDocument to)
{
    TextRange range = new TextRange(from.ContentStart, from.ContentEnd);
    MemoryStream stream = new MemoryStream();
    System.Windows.Markup.XamlWriter.Save(range, stream);
    range.Save(stream, DataFormats.XamlPackage);
    TextRange range2 = new TextRange(to.ContentEnd, to.ContentEnd);
    range2.Load(stream, DataFormats.XamlPackage);
}

This was copied from:

http://social.msdn.microsoft.com/Forums/en/wpf/thread/f4b26d9b-5b74-446b-85e7-e49e519380ad




回答2:


Just to add to the answer, if you want to move rather than copy:

You can't just add elements to the destination document, as then they will be in both documents - so you need to remove them from the source document first.

using System.Linq;
...

var blockList = source.Blocks.ToList();
foreach (var block in blockList)
{
    source.Blocks.Remove(block);
    dest.Blocks.Add(block);
}

(Implementation note: We put references to the blocks to process into a separate list first to avoid changing the source.Blocks list while enumerating it in the foreach)



来源:https://stackoverflow.com/questions/1796821/copying-one-flowdocument-to-second-flowdocument

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!