sourceDocument = (FlowDocument)XamlReader.Load(memoryStream); // foreach (Block aBlock in sourceDocument.Blocks) { targetDocument.Blocks.Add(aBlock); }
But the above code broke with this exception
An exception of type ‘System.InvalidOperationException’ occurred and was caught. Collection was modified; enumeration operation may not execute.
Not sure the reason why the exception is raising when we loop through the Blocks of FlowDocument and add them to the another FlowDocument. But i resolved the issue by converting the Blocks of source object to List and then adding them to the target FlowDocument. Here is the code that worked
// sourceDocument = (FlowDocument)XamlReader.Load(memoryStream); // List<Block> flowDocumentBlocks = new List<Block>(sourceDocument.Blocks);
// foreach (Block aBlock in flowDocumentBlocks) { targetDocument.Blocks.Add(aBlock); }
Hope this piece of code helps you.