Search code examples
wpfrichtextboxtextblockflowdocument

WPF FlowDocument to InlineCollection


I want to create a small in Place Editor in a WPF Application for TextBox Texts. For this I want to use the RichTextBox. As the RichTextBox works with a FlowDocument, and the TextBlock with a InlineCollection, this does not work. Is there a easy way to Convert the RichtextBox Document to a InlineCollection? (If I only allow RTB Content wich is supported in a Inline?)


Solution

  • Something like the following extension method could be used to extract all Inlines from a FlowDocument. You might need to add some extra whitespace inlines to separate the paragraphs and sections.

    public static class FlowDocumentEx
    {
        public static ICollection<Inline> GetInlines(this FlowDocument doc)
        {
            return GetInlines(doc.Blocks);
        }
    
        public static ICollection<Inline> GetInlines(TextElementCollection<Block> blocks)
        {
            var inlines = new List<Inline>();
    
            foreach (var block in blocks)
            {
                if (block is Paragraph)
                {
                    inlines.AddRange(((Paragraph)block).Inlines);
                }
                else if (block is Section)
                {
                    inlines.AddRange(GetInlines(((Section)block).Blocks));
                }
            }
    
            return inlines;
        }
    }
    

    You would use it like this:

    textBlock.Inlines.Clear();
    textBlock.Inlines.AddRange(richTextBox.Document.GetInlines());