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 ital
There are various Inline elements that can help you, for the simplest formatting options you can use Bold, Italic and Underline:
Sample text with bold , italic and underlined words.
I think it is worth noting, that those elements are in fact just shorthands for Span elements with various properties set (i.e.: for Bold
, the FontWeight
property is set to FontWeights.Bold
).
This brings us to our next option: the aforementioned Span element.
You can achieve the same effects with this element as above, but you are granted even more possibilities; you can set (among others) the Foreground
or the Background
properties:
Sample text with bold, italic and underlined words. Coloring is also possible.
The Span
element may also contain other elements like this:
Italic text with some coloring.
There is another element, which is quite similar to Span
, it is called Run. The Run
cannot contain other inline elements while the Span
can, but you can easily bind a variable to the Run
's Text
property:
Username:
Also, you can do the whole formatting from code-behind if you prefer:
TextBlock tb = new TextBlock();
tb.Inlines.Add("Sample text with ");
tb.Inlines.Add(new Run("bold") { FontWeight = FontWeights.Bold });
tb.Inlines.Add(", ");
tb.Inlines.Add(new Run("italic ") { FontStyle = FontStyles.Italic });
tb.Inlines.Add("and ");
tb.Inlines.Add(new Run("underlined") { TextDecorations = TextDecorations.Underline });
tb.Inlines.Add("words.");