using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows.Documents; namespace Demos.Warden.TagTextEditing { public class FlowDocumentWalker { public delegate void ElementAction(TagBaseElement element, Inline inlineOwner); public Exception[] PerformActionOnTagElements(FlowDocument document, ElementAction actionOnTagElement) { List encounteredCatchedExceptions = new List(); Block[] blocks = document.Blocks.ToArray(); foreach (Block block in blocks) { encounteredCatchedExceptions.AddRange(this.performActionOnTEBlocks(block, actionOnTagElement)); } return encounteredCatchedExceptions.ToArray(); } private Exception[] performActionOnTEBlocks(Block block, ElementAction action) { List encounteredCatchedExceptions = new List(); try { if (block is Paragraph) { encounteredCatchedExceptions.AddRange(this.performActionOnTEInParagraph((Paragraph)block, action)); } else if (block is Table) { encounteredCatchedExceptions.AddRange(this.performActionOnTEInTable((Table)block, action)); } else { encounteredCatchedExceptions.Add(new NotImplementedException(String.Format("Conversion method for block of type {0} is missing.", block.GetType()))); } } catch (Exception exception) { encounteredCatchedExceptions.Add(exception); } return encounteredCatchedExceptions.ToArray(); } private Exception[] performActionOnTEInParagraph(Paragraph paragraph, ElementAction action) { List encounteredCatchedExceptions = new List(); Inline[] inlines = paragraph.Inlines.ToArray(); foreach (Inline curInline in inlines) { if (!(curInline is TagBaseElement)) { continue; } TagBaseElement myElement = (TagBaseElement)curInline; action(myElement, curInline); } return encounteredCatchedExceptions.ToArray(); } private Exception[] performActionOnTEInTable(Table table, ElementAction action) { List encounteredCatchedExceptions = new List(); try { foreach (TableRowGroup trg in table.RowGroups) { foreach (TableRow tr in trg.Rows) { foreach (TableCell tc in tr.Cells) { foreach (Block block in tc.Blocks.ToArray()) { encounteredCatchedExceptions.AddRange(this.performActionOnTEBlocks(block, action)); } } } } } catch (Exception ex) { encounteredCatchedExceptions.Add(ex); } return encounteredCatchedExceptions.ToArray(); } } }