#244 – Use a TextBlock Element for Richer Formatting

The Label control allows setting font properties like size and weight, but the settings apply to all of the text in the label.  Also, it’s difficult to embed line breaks without introducing cryptic characters.

The TextBlock control allows formatting subsets of its textual content by adding a series of Run elements and formatting each one separately.

Here’s an example.  Here’s a Label control:

		<Label Background="DarkGray" Margin="10" Height="50" FontSize="14"
			Content="Lancaster / York Richard, Duke of York Henry VI Warwick Somerset" />


And here’s an example of a TextBlock control, showing the same content:

		<TextBlock Background="DarkGray" Margin="10" Height="100" FontSize="14">
			<Run Text="Lancaster" Foreground="Red" TextDecorations="Underline"/><Run Text=" / "/>
			<Run Text="York" Foreground="White" TextDecorations="Underline"/>
			<LineBreak/>
			<Run Text="Richard, Duke of York" Foreground="White" FontSize="16" FontWeight="Bold"/>
			<LineBreak/>
			<Run Text="Henry VI" Foreground="Red" FontSize="16" FontWeight="Bold"/>
			<LineBreak/>
			<Run Text="Warwick" Foreground="White" FontStyle="Italic"/>
			<LineBreak/>
			<Run Text="Somerset" Foreground="Red" FontStyle="Italic"/>
		</TextBlock>

Advertisement

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

One Response to #244 – Use a TextBlock Element for Richer Formatting

  1. Pingback: #245 – Easily Inline Text Formatting Codes with TextBlock Control « 2,000 Things You Should Know About WPF

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: