Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Formatting text in a TextBlock

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.

like image 620
Ash Avatar asked Mar 10 '11 16:03

Ash


People also ask

Is TextBlock editable?

TextBlock is not editable.

What is advanced text formatting?

The text layout and UI controls in WPF provide formatting properties that allow you to easily include formatted text in your application. These controls expose a number of properties to handle the presentation of text, which includes its typeface, size, and color.

How do you make a string bold in C#?

Wrap a word in string with '<b>' to make it Bold without changing word's original case.


2 Answers

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).

like image 79
ChrisF Avatar answered Oct 23 '22 17:10

ChrisF


You can do this in XAML easily enough:

<TextBlock>   Hello <Bold>my</Bold> faithful <Underline>computer</Underline>.<Italic>You rock!</Italic> </TextBlock> 
like image 28
Ashley Davis Avatar answered Oct 23 '22 18:10

Ashley Davis