How To Merge Two FlowDocument Objects Using C# Code[WPF]

本文介绍了一种将一个FlowDocument对象的内容追加到另一个FlowDocument对象的方法。直接遍历并添加会导致异常,通过先转换为List再添加可以解决问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

As part of one of requirements in our application we had to appended a FlowDocument objects to another FlowDocument object. The requirement looked very simple and I tried the following which loops through the Blocks of source FlowDocument and appends them to target FlowDocument object.


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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值