WPF TextBlock Control


The TextBlock allows you to put text on the screen, much like a Label control does. A common understanding is that a Label is for short, one-line texts (but may include e.g. an image), while the TextBlock works very well for multiline strings as well, but can only contain text (strings). The TextBlock works well along with the WrapPanel to when you want to display text in two parts: a short description and the value. For example: The amount is $45.76.

The TextBlock content property is not its Text property but rather a collection of objects called inlines. A simple string inside the two TextBlock elements is really a collection with one element called Run. All of the three lines of XAML code below do the same thing: display the text to the screen.

<StackPanel>
    <TextBlock>A simple string.</TextBlock>
    <TextBlock><Run Text="Run is just a bunch of text with identical formatting"></Run></TextBlock>
    <TextBlock><Run>Text is Run's</Run><Run> content property</Run></TextBlock>
</StackPanel>

Since the content property is really just a collection of Run, you can have multiple <Run> sets of tags inside the TextBlock.

TextBlock Example

Below is a screenshot of an example program called TextBlockExample. This interface has one StackPanel with a number of Textblocks. All of the text that you see here is from TextBlocks, except of course the title in the main window.

Here is the XAML code. This uses many TextBlocks. Alternatively you can use <LineBreak/> to force e new line.

<Window x:Class="TextBlockExample.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:TextBlockExample"
        mc:Ignorable="d"
        WindowStartupLocation="CenterScreen"
        Title="TextBlockExample" Height="400" Width="620">
    <StackPanel Name="sp" Margin="10" Background="WhiteSmoke">
        <TextBlock>Hey</TextBlock>
        <TextBlock Foreground="Blue" FontWeight="Bold">Hey there</TextBlock>
        <TextBlock Text="text property"></TextBlock>
        <TextBlock TextTrimming="CharacterEllipsis">No wrapping...Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum ullamcorper libero ligula, vel pulvinar libero fringilla vel. Nam quis nibh sit amet orci fermentum vulputate. Nullam id risus sem. Nullam cursus metus sed velit aliquet elementum. Cras sodales orci lectus, eget iaculis quam auctor ut. Donec mattis posuere nibh. Etiam ac dui purus. Quisque posuere urna a augue malesuada consequat. Phasellus at mi imperdiet, euismod nisl ac, convallis magna. Duis pharetra turpis quis nibh vehicula eleifend. In pellentesque diam sagittis nunc faucibus, ac consectetur felis pellentesque. Sed vehicula in lectus a pellentesque. Duis nec bibendum eros, at accumsan odio. Maecenas dui sem, luctus at est nec, consequat mattis lacus. Interdum et malesuada fames ac ante ipsum primis in faucibus. Duis felis eros, sagittis condimentum congue nec, ullamcorper volutpat nisl.</TextBlock>
        <TextBlock TextWrapping="Wrap">Wrapping...Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum ullamcorper libero ligula, vel pulvinar libero fringilla vel. Nam quis nibh sit amet orci.</TextBlock>
        <TextBlock>This is a TextBlock control<LineBreak />with multiple lines of text.</TextBlock>
        <TextBlock TextWrapping="Wrap">
			TextBlock with <Bold>bold</Bold>, <Italic>italic</Italic> and <Underline>underlined</Underline> text, showing us that the TextBlock control supports inline content.
        </TextBlock>
        <TextBlock TextWrapping="Wrap">
			This <Span FontWeight="Bold">is</Span> a
			<Span Background="Silver" Foreground="Maroon">TextBlock</Span>
			with <Span TextDecorations="Underline">several</Span>
			<Span FontStyle="Italic">Span</Span> elements,
			<Span Foreground="Blue">
				using a <Bold>variety</Bold> of <Italic>styles</Italic>, allowing you to set almost any kind of specific rendering, 
                including font size, style and weight, background and foreground colors and so on. 
                The Span element allows other inline elements inside of it, making it easy to do even advanced combinations of text and style. 
			</Span>.
        </TextBlock>
        <TextBlock>
            <Run FontStyle="Italic">Run FontStyle Italic</Run>
            <Run FontStyle="Oblique" FontFamily="Courier New">Oblique Courier New</Run>
            <Run TextDecorations="Underline"> underline</Run>
            <Span Background="Silver" Foreground="Red">Span background Silver Foreground Red</Span>
        </TextBlock>
        <TextBlock Name="txtB" Text=""></TextBlock>
    </StackPanel>
</Window>

Below is the code behind.

using System.Windows;
using System.Windows.Documents;
using System.Windows.Media;
namespace TextBlockExample
{
    public partial class MainWindow : Window
    {
        public static MainWindow win { get; set; }
        public MainWindow()
        {
            InitializeComponent();

            win = (MainWindow)Application.Current.MainWindow;
            win.txtB.TextWrapping = TextWrapping.Wrap;
            win.txtB.Margin = new Thickness(20);
            win.txtB.Inlines.Add("An example from the website Wpf-Tutorial.com on ");
            win.txtB.Inlines.Add(new Run("the TextBlock control ") { FontWeight = FontWeights.Bold });
            win.txtB.Inlines.Add("using ");
            win.txtB.Inlines.Add(new Run("inline ") { FontStyle = FontStyles.Italic });
            win.txtB.Inlines.Add(new Run("text formatting ") { Foreground = Brushes.Blue });
            win.txtB.Inlines.Add("from ");
            win.txtB.Inlines.Add(new Run("Code-Behind") { TextDecorations = TextDecorations.Underline });
            win.txtB.Inlines.Add(". So this is cool because we can set text and format that text as we want from our C# code " +
                "behind. I've used this technique to display some file processing results to the user in a program called" +
                " HFTE. This program reads in an HTML file and scrapes for all the data in all of the HTML tables." +
                " The file processing results are not known until run time, not design time.");
        }
    }
}