Finding all Images in a FlowDocument

后端 未结 4 1796
花落未央
花落未央 2020-12-19 17:34

Since I am pretty new to WPF FlowDocuments I would like to ask if the code below is correct. It is supposed to return all Images contained in a FlowDocument as List:

4条回答
  •  庸人自扰
    2020-12-19 18:14

    Little change in Code to add coverage for List

        public static IEnumerable FindImages(FlowDocument document)
        {
            return document.Blocks.SelectMany(block => FindImages(block));
        }
    
        public static IEnumerable FindImages(Block block)
        {
            if (block is Table)
            {
                return ((Table)block).RowGroups
                    .SelectMany(x => x.Rows)
                    .SelectMany(x => x.Cells)
                    .SelectMany(x => x.Blocks)
                    .SelectMany(innerBlock => FindImages(innerBlock));
            }
            if (block is Paragraph)
            {
                return ((Paragraph)block).Inlines
                    .OfType()
                    .Where(x => x.Child is Image)
                    .Select(x => x.Child as Image);
            }
            if (block is BlockUIContainer)
            {
                Image i = ((BlockUIContainer)block).Child as Image;
                return i == null
                            ? new List()
                            : new List(new[] { i });
            }
            if (block is List)
            {
                return ((List)block).ListItems.SelectMany(listItem => listItem
                                                                      .Blocks
                                                                      .SelectMany(innerBlock => FindImages(innerBlock)));
            }
            throw new InvalidOperationException("Unknown block type: " + block.GetType());
        }
    

提交回复
热议问题