Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / desktop / WPF

WPF RichTextBox features in TextBlock

3.00/5 (2 votes)
28 Feb 2010CPOL 1  
In WPF, the TextBlock is used to display simple text. We can apply several formatting to the text like Bold, Italics or Underline to name a few.But it is a little known fact that it is possible to display several differently formatted text in a SINGLE TextBlock!!!for e.g. you can make a...
In WPF, the TextBlock is used to display simple text. We can apply several formatting to the text like Bold, Italics or Underline to name a few.

But it is a little known fact that it is possible to display several differently formatted text in a SINGLE TextBlock!!!
for e.g. you can make a TextBlock display the following text

This is a simple multiformat text!


This can be achieved by using multiple Run.

Normally when you assign a text to the TextBlock, it creates a single Run which encapsulates the text assigned.

In order to add multiformatted text to a TextBlock, you have to create several Runs and add them to the TextBlock's Inlines property.

Here is an example

Run run1 = new Run("This is ");

Run run2 = new Run("bold");
run2.FontWeight = FontWeights.Bold;

Run run3 = new Run(" and ");

Run run4 = new Run("italic");
run4.FontStyle = FontStyles.Italic;

Run run5 = new Run("text.");

myTextBlock.Inlines.Add(run1);
myTextBlock.Inlines.Add(run2);
myTextBlock.Inlines.Add(run3);
myTextBlock.Inlines.Add(run4);
myTextBlock.Inlines.Add(run5);

This will set the myTextBlock as

This is bold and italic text.

More information on TextBlock can be found here[^].

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)