Issue in setting the vertical alignment for the text in RichTextBox WPF

Viewed 748

In RichTextBox WPF, there is an issue while setting the vertical alignment for the content. I have tried setting Vertical Content alignment and TextAlignment for the document, but still it does not work. The vertical alignment is still aligned at the top position and not at the center position.

Please find the code example for reference of setting alignment,

        FlowDocument mcFlowDoc = new FlowDocument();
        // Create a paragraph with text  
        Paragraph para = new Paragraph();
        para.Inlines.Add(new Run("Flow Document\n"));
        para.Inlines.Add(new Bold(new Run("Content is not aligned\n.")));
        para.Inlines.Add(new Run("Vertical content alignment does not work in RichTextBox\n"));

        // Add the paragraph to blocks of paragraph  
        mcFlowDoc.Blocks.Add(para);

        // Set contents  
        richtextbox.Document = mcFlowDoc;

        //Set Alignment,


        richtextbox.VerticalContentAlignment = VerticalAlignment.Center;
        richtextbox.HorizontalContentAlignment = HorizontalAlignment.Center;
        richtextboxt.Document.TextAlignment = TextAlignment.Center;

Anyone interested, can you please suggest idea on this?

1 Answers

You can try to set alignment for FlowDocument instead of RichTextBox.
Take a look at the code below.

    FlowDocument mcFlowDoc = new FlowDocument();

    // Set alignment
    mcFlowDoc.TextAlignment = TextAlignment.Center;

    // Create a paragraph with text  
    Paragraph para = new Paragraph();
    para.Inlines.Add(new Run("Flow Document\n"));
    para.Inlines.Add(new Bold(new Run("Content is not aligned\n.")));
    para.Inlines.Add(new Run("Vertical content alignment does not work in RichTextBox\n"));

    // Add the paragraph to blocks of paragraph  
    mcFlowDoc.Blocks.Add(para);

    // Set contents  
    richTextBox.Document = mcFlowDoc;

You can also set Padding property on RichTextBox control as Kevin Pan mentioned here

Related