WPF - how to add text in a richtextbox

You mighyt have noticed that the RichTextBox control in WPF does not have a Text or Content method. so you will have to use something a little bit different. This method is usefull when you use a read only richtextbox and you want formated text in it.

First you'll have to initialize a paragraph, then add the string inside the paragraph and lastly add the paragraph to the richtextbox.

In the bellow example I will show you how to add a specific text in a richtextbox when a button is clicked.

private void btnAddText_Click(object sender, RoutedEventArgs e)
        {
//we want to clear all text inside the richtextbox, or else each time we click the button the same text will be added over and over again

            txtRichTextBox.Document.Blocks.Clear(); 

//We initialize 3 paragraphs

            Paragraph textTitle = new Paragraph();
            Paragraph textSubTitle = new Paragraph();
            Paragraph textDescription = new Paragraph();

//We will add the strings to the paragraphs as well as bolding the first and justifying the 3rd

            textTitle.Inlines.Add("This is a bolded title");
            textTitle.FontWeight = FontWeights.Bold;
            textSubTitle.Inlines.Add("This is a subtitle");
            textDescription.Inlines.Add("This is a long text so in case you'll copy paste this code you will notice how the text is justified. Just remember not to make the richtextbox too big.");
            textDescription.TextAlignment = TextAlignment.Justify;

//And here we add all 3 paragraphs to the rich text box

            txtRichTextBox.Document.Blocks.Add(textTitle);
            txtRichTextBox.Document.Blocks.Add(textSubTitle);
            txtRichTextBox.Document.Blocks.Add(textDescription);        
}

5 comments:

  1. This comment has been removed by a blog administrator.

    ReplyDelete
  2. KetticRichTextBox can import text from a variety of document formats including html, doc, rtf, and pdf.

    ReplyDelete
  3. Man .. you are great..
    I am searching for this issue overall websites .. no solution

    you provide the best tutorial

    ReplyDelete