BlackWaspTM

This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

Windows Presentation Foundation
.NET 4.0+

WPF Information Controls - TextBlock Basics

The forty-first part of the Windows Presentation Foundation Fundamentals tutorial begins to look at another of the WPF user information controls. This time it's the TextBlock control, which allows the display of short text items with formatting.

Padding

Another property that is usually provided by the Control class and that is recreated in TextBlock is Padding. This creates an inner margin between the edges of the TextBlock and the text it contains. You can set a single value to be applied to every edge, two values to allow the top and bottom padding to differ from the left and right edges, or four values to independently control each edge's padding.

The updated tag below adds ten pixels of padding around the entire TextBlock.

<TextBlock Foreground="SeaGreen"
           Background="SeaShell"
           TextWrapping="Wrap"
           TextAlignment="Justify"
           FontFamily="Times New Roman"
           FontSize="24"
           FontStyle="Italic"
           FontWeight="Bold"
           Padding="10">

The results are shown below. Note that the text reaches the bottom edge of the window. This is because the TextBlock extends beyond the confines of the window. If you make the window large enough to see all of the text, you will be able to observe the padding at the bottom of the control.

WPF TextBlock control with padding

Line Height

The final property that we'll consider in this article is LineHeight. This allows you to adjust the height of each line of text, which can improve the readability in some cases. The LineHeight property can be set using a simple number to specify a height in pixels. You can also add units to the value, allowing you to set a line height in inches (in), centimetres (cm), points (pt) or pixels (px).

The final example expands the line height for the text to one centimetre:

<TextBlock Foreground="SeaGreen"
           Background="SeaShell"
           TextWrapping="Wrap"
           TextAlignment="Justify"
           FontFamily="Times New Roman"
           FontSize="24"
           FontStyle="Italic"
           FontWeight="Bold"
           Padding="10"
           LineHeight="1cm">

Run the program to see the results. You should be able to see that the space between the lines has increased slightly.

WPF TextBlock control with expanded line height

26 December 2013