获取包含Block对象的BlockCollection对象

时间:2010-10-28 18:43:16

标签: wpf flowdocument

获取包含给定Block类型对象的BlockCollection对象(System.Windows.Documents命名空间)的简单方法(也可能是快速方式)是什么?

我找不到使用Block类提供的任何直接方法。

public static BlockCollection FindContainingCollection(Block block)
{
   // ???        
}

3 个答案:

答案 0 :(得分:1)

因为我发布这个已经过了一个月并没有得到答案,我会发布我最终做的事情。我用这种方式编写是相当愚蠢的,但是我无法找到任何更简洁的方法来实现它,主要是因为Blocks属性不是通过公共接口公开的。

    public BlockCollection FindContainingCollection(Block block)
    {
        BlockCollection blocks = null;

        FlowDocument flowDoc = block.Parent as FlowDocument;

        if (flowDoc != null)
            blocks = flowDoc.Blocks;
        else
        {
            TableCell tableCell = block.Parent as TableCell;
            if (tableCell != null)
                blocks = tableCell.Blocks;
            else
            {
                ListItem listItem = block.Parent as ListItem;
                if (listItem != null)
                    blocks = listItem.Blocks;
                else
                {
                    Section section = block.Parent as Section;
                    if (section != null)
                        blocks = section.Blocks;
                    else
                    {
                        Figure figure = block.Parent as Figure;
                        if (figure != null)
                            blocks = figure.Blocks;
                        else
                        {
                            Floater floater = block.Parent as Floater;
                            if (floater != null)
                                blocks = floater.Blocks;
                        }
                    }
                }
            }
        }

        return blocks;
    }

答案 1 :(得分:0)

使用ElementAt(int32)

for(int i = 0; i < blocks.Count; i++) {
    Block block = blocks.ElementAt(i);
    Console.WriteLine("{0}", block.GetType());
}

答案 2 :(得分:-1)

Block有一个属性SiblingBlocks,可以满足您的需求。

BlockCollection containingCollection = block.SiblingBlocks

https://msdn.microsoft.com/en-us/library/system.windows.documents.block.siblingblocks(v=vs.100).aspx