Formatting text in a TextBlock

Ash picture Ash · Mar 10, 2011 · Viewed 141.4k times · Source

How do I achieve formatting of a text inside a TextBlock control in my WPF application?

e.g.: I would like to have certain words in bold, others in italic, and some in different colors, like this example:

enter image description here

The reason behind my question is this actual problem:

lblcolorfrom.Content = "Colour From: " + colourChange.ElementAt(3).Value.ToUpper();

I would like the second part of the string to be bold, and I know that I could use two controls (Labels, TextBlocks, etc.) but I'd rather not, due the vast amount of controls already in use.

Answer

ChrisF picture ChrisF · Mar 10, 2011

You need to use Inlines:

<TextBlock.Inlines>
    <Run FontWeight="Bold" FontSize="14" Text="This is WPF TextBlock Example. " />
    <Run FontStyle="Italic" Foreground="Red" Text="This is red text. " />
</TextBlock.Inlines>

With binding:

<TextBlock.Inlines>
    <Run FontWeight="Bold" FontSize="14" Text="{Binding BoldText}" />
    <Run FontStyle="Italic" Foreground="Red" Text="{Binding ItalicText}" />
</TextBlock.Inlines>

You can also bind the other properties:

<TextBlock.Inlines>
    <Run FontWeight="{Binding Weight}"
         FontSize="{Binding Size}"
         Text="{Binding LineOne}" />
    <Run FontStyle="{Binding Style}"
         Foreground="Binding Colour}"
         Text="{Binding LineTwo}" />
</TextBlock.Inlines>

You can bind through converters if you have bold as a boolean (say).