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:
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.
TextBlock is not editable.
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.
Wrap a word in string with '<b>' to make it Bold without changing word's original case.
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).
You can do this in XAML easily enough:
<TextBlock> Hello <Bold>my</Bold> faithful <Underline>computer</Underline>.<Italic>You rock!</Italic> </TextBlock>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With