如何通过 Blocks 属性操作流内容元素

这些示例演示了可通过 Blocks 属性对流内容元素执行的一些更常见的操作。 此属性用于在 BlockCollection中添加和删除项。 具有 Blocks 属性的流内容元素包括:

这些示例恰好用作 Section 流内容元素,但这些技术适用于托管流内容元素集合的所有元素。

创建新分区

以下示例新建一个 Section ,然后使用 Add 方法向 Section 内容添加新的 Paragraph。

Section secx = new Section();
secx.Blocks.Add(new Paragraph(new Run("A bit of text content...")));
Dim secx As New Section()
secx.Blocks.Add(New Paragraph(New Run("A bit of text content...")))

创建新的段落元素

以下示例创建一个新的 Paragraph 元素,并将其插入到 Section的开头。

Paragraph parx = new Paragraph(new Run("Text to insert..."));
secx.Blocks.InsertBefore(secx.Blocks.FirstBlock, parx);
Dim parx As New Paragraph(New Run("Text to insert..."))
secx.Blocks.InsertBefore(secx.Blocks.FirstBlock, parx)

获取节中的顶级块元素

下面的示例获取 Block 中包含的顶级 Section 元素数。

int countTopLevelBlocks = secx.Blocks.Count;
Dim countTopLevelBlocks As Integer = secx.Blocks.Count

删除该部分中的最后一个块元素

以下示例删除 Block中的最后一个 Section 元素。

secx.Blocks.Remove(secx.Blocks.LastBlock);
secx.Blocks.Remove(secx.Blocks.LastBlock)

清除节中的所有 Block 元素内容

以下示例将 Block中的所有内容(Section 元素)清除。

secx.Blocks.Clear();
secx.Blocks.Clear()

另请参阅