How to create a WPF RichTextBox Dynamically?

The code listed in Listing 1 creates a FlowDocument, adds a paragraph to the flow document and sets the Document property of the RichTextBox as FlowDocument.

private void CreateAndLoadRichTextBox()

{

    // Create a FlowDocument

    FlowDocument mcFlowDoc = new FlowDocument();

 

    // Create a paragraph with text

    Paragraph para = new Paragraph();

    para.Inlines.Add(new Run("I am a flow document. Would you like to edit me? "));

    para.Inlines.Add(new Bold(new Run("Go ahead.")));

 

    // Add the paragraph to blocks of paragraph

    mcFlowDoc.Blocks.Add(para);

 

    // Create RichTextBox, set its hegith and width

    RichTextBox mcRTB = new RichTextBox();

    mcRTB.Width = 560;

    mcRTB.Height = 280;

 

    // Set contents

    mcRTB.Document = mcFlowDoc;

 

    // Add RichTextbox to the container

    ContainerPanel.Children.Add(mcRTB);    

}

Listing 1.