Xamarin.Forms Label

Download Sample Download the sample

Display text in Xamarin.Forms

The Label view is used for displaying text, both single and multi-line. Labels can have text decorations, colored text, and use custom fonts (families, sizes, and options).

Text decorations

Underline and strikethrough text decorations can be applied to Label instances by setting the Label.TextDecorations property to one or more TextDecorations enumeration members:

  • None
  • Underline
  • Strikethrough

The following XAML example demonstrates setting the Label.TextDecorations property:

<Label Text="This is underlined text." TextDecorations="Underline"  />
<Label Text="This is text with strikethrough." TextDecorations="Strikethrough" />
<Label Text="This is underlined text with strikethrough." TextDecorations="Underline, Strikethrough" />

The equivalent C# code is:

var underlineLabel = new Label { Text = "This is underlined text.", TextDecorations = TextDecorations.Underline };
var strikethroughLabel = new Label { Text = "This is text with strikethrough.", TextDecorations = TextDecorations.Strikethrough };
var bothLabel = new Label { Text = "This is underlined text with strikethrough.", TextDecorations = TextDecorations.Underline | TextDecorations.Strikethrough };

The following screenshots show the TextDecorations enumeration members applied to Label instances:

Note

Text decorations can also be applied to Span instances. For more information about the Span class, see Formatted Text.

Colors

Labels can be set to use a custom text color via the bindable TextColor property.

Special care is necessary to ensure that colors will be usable on each platform. Because each platform has different defaults for text and background colors, you'll need to be careful to pick a default that works on each.

The following XAML example sets the text color of a Label:

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="TextSample.LabelPage"
             Title="Label Demo">
    <StackLayout Padding="5,10">
      <Label TextColor="#77d065" FontSize = "20" Text="This is a green label." />
    </StackLayout>
</ContentPage>

The equivalent C# code is:

public partial class LabelPage : ContentPage
{
    public LabelPage ()
    {
        InitializeComponent ();

        var layout = new StackLayout { Padding = new Thickness(5,10) };
        var label = new Label { Text="This is a green label.", TextColor = Color.FromHex("#77d065"), FontSize = 20 };
        layout.Children.Add(label);
        this.Content = layout;
    }
}

The following screenshots show the result of setting the TextColor property:

For more information about colors, see Colors.

Fonts

For more information about specifying fonts on a Label, see Fonts.

Truncation and wrapping

Labels can be set to handle text that can't fit on one line in one of several ways, exposed by the LineBreakMode property. LineBreakMode is an enumeration with the following values:

  • HeadTruncation – truncates the head of the text, showing the end.
  • CharacterWrap – wraps text onto a new line at a character boundary.
  • MiddleTruncation – displays the beginning and end of the text, with the middle replace by an ellipsis.
  • NoWrap – does not wrap text, displaying only as much text as can fit on one line.
  • TailTruncation – shows the beginning of the text, truncating the end.
  • WordWrap – wraps text at the word boundary.

Displaying a specific number of lines

The number of lines displayed by a Label can be specified by setting the Label.MaxLines property to a int value:

  • When MaxLines is 0, the Label respects the value of the LineBreakMode property to either show just one line, possibly truncated, or all lines with all text.
  • When MaxLines is 1, the result is identical to setting the LineBreakMode property to NoWrap, HeadTruncation, MiddleTruncation, or TailTruncation. However, the Label will respect the value of the LineBreakMode property with regard to placement of an ellipsis, if applicable.
  • When MaxLines is greater than 1, the Label will display up to the specified number of lines, while respecting the value of the LineBreakMode property with regard to placement of an ellipsis, if applicable. However, setting the MaxLines property to a value greater than 1 has no effect if the LineBreakMode property is set to NoWrap.

The following XAML example demonstrates setting the MaxLines property on a Label:

<Label Text="Lorem ipsum dolor sit amet, consectetur adipiscing elit. In facilisis nulla eu felis fringilla vulputate. Nullam porta eleifend lacinia. Donec at iaculis tellus."
       LineBreakMode="WordWrap"
       MaxLines="2" />

The equivalent C# code is:

var label =
{
  Text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. In facilisis nulla eu felis fringilla vulputate. Nullam porta eleifend lacinia. Donec at iaculis tellus.", LineBreakMode = LineBreakMode.WordWrap,
  MaxLines = 2
};

The following screenshots show the result of setting the MaxLines property to 2, when the text is long enough to occupy more than 2 lines:

Formatted text

Labels expose a FormattedText property which allows the presentation of text with multiple fonts and colors in the same view.

The FormattedText property is of type FormattedString, which comprises one or more Span instances, set via the Spans property. The following Span properties can be used to set visual appearance:

  • BackgroundColor – the color of the span background.
  • Font – the font for the text in the span.
  • FontAttributes – the font attributes for the text in the span.
  • FontFamily – the font family to which the font for the text in the span belongs.
  • FontSize – the size of the font for the text in the span.
  • ForegroundColor – the color for the text in the span. This property is obsolete and has been replaced by the TextColor property.
  • LineHeight - the multiplier to apply to the default line height of the span. For more information, see Line Height.
  • Style – the style to apply to the span.
  • Text – the text of the span.
  • TextColor – the color for the text in the span.
  • TextDecorations - the decorations to apply to the text in the span. For more information, see Text Decorations.

In addition, the GestureRecognizers property can be used to define a collection of gesture recognizers that will respond to gestures on the Span.

The following XAML example demonstrates a FormattedText property that consists of three Span instances:

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="TextSample.LabelPage"
             Title="Label Demo - XAML">
    <StackLayout Padding="5,10">
        ...
        <Label LineBreakMode="WordWrap">
            <Label.FormattedText>
                <FormattedString>
                    <Span Text="Red Bold, " TextColor="Red" FontAttributes="Bold" />
                    <Span Text="default, " Style="{DynamicResource BodyStyle}">
                        <Span.GestureRecognizers>
                            <TapGestureRecognizer Command="{Binding TapCommand}" />
                        </Span.GestureRecognizers>
                    </Span>
                    <Span Text="italic small." FontAttributes="Italic" FontSize="Small" />
                </FormattedString>
            </Label.FormattedText>
        </Label>
    </StackLayout>
</ContentPage>

The equivalent C# code is:

public class LabelPageCode : ContentPage
{
    public LabelPageCode ()
    {
        var layout = new StackLayout{ Padding = new Thickness (5, 10) };
        ...
        var formattedString = new FormattedString ();
        formattedString.Spans.Add (new Span{ Text = "Red bold, ", ForegroundColor = Color.Red, FontAttributes = FontAttributes.Bold });

        var span = new Span { Text = "default, " };
        span.GestureRecognizers.Add(new TapGestureRecognizer { Command = new Command(async () => await DisplayAlert("Tapped", "This is a tapped Span.", "OK")) });
        formattedString.Spans.Add(span);
        formattedString.Spans.Add (new Span { Text = "italic small.", FontAttributes = FontAttributes.Italic, FontSize =  Device.GetNamedSize(NamedSize.Small, typeof(Label)) });

        layout.Children.Add (new Label { FormattedText = formattedString });
        this.Content = layout;
    }
}

Important

The Text property of a Span can be set through data binding. For more information, see Data Binding.

Note that a Span can also respond to any gestures that are added to the span's GestureRecognizers collection. For example, a TapGestureRecognizer has been added to the second Span in the above code examples. Therefore, when this Span is tapped the TapGestureRecognizer will respond by executing the ICommand defined by the Command property. For more information about gesture recognizers, see Xamarin.Forms Gestures.

The following screenshots show the result of setting the FormattedString property to three Span instances:

Line height

The vertical height of a Label and a Span can be customized by setting the Label.LineHeight property or Span.LineHeight to a double value. On iOS and Android these values are multipliers of the original line height, and on the Universal Windows Platform (UWP) the Label.LineHeight property value is a multiplier of the label font size.

Note

The following XAML example demonstrates setting the LineHeight property on a Label:

<Label Text="Lorem ipsum dolor sit amet, consectetur adipiscing elit. In facilisis nulla eu felis fringilla vulputate. Nullam porta eleifend lacinia. Donec at iaculis tellus."
       LineBreakMode="WordWrap"
       LineHeight="1.8" />

The equivalent C# code is:

var label =
{
  Text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. In facilisis nulla eu felis fringilla vulputate. Nullam porta eleifend lacinia. Donec at iaculis tellus.", LineBreakMode = LineBreakMode.WordWrap,
  LineHeight = 1.8
};

The following screenshots show the result of setting the Label.LineHeight property to 1.8:

The following XAML example demonstrates setting the LineHeight property on a Span:

<Label LineBreakMode="WordWrap">
    <Label.FormattedText>
        <FormattedString>
            <Span Text="Lorem ipsum dolor sit amet, consectetur adipiscing elit. In a tincidunt sem. Phasellus mollis sit amet turpis in rutrum. Sed aliquam ac urna id scelerisque. "
                  LineHeight="1.8"/>
            <Span Text="Nullam feugiat sodales elit, et maximus nibh vulputate id."
                  LineHeight="1.8" />
        </FormattedString>
    </Label.FormattedText>
</Label>

The equivalent C# code is:

var formattedString = new FormattedString();
formattedString.Spans.Add(new Span
{
  Text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. In a tincidunt sem. Phasellus mollis sit amet turpis in rutrum. Sed aliquam ac urna id scelerisque. ",
  LineHeight = 1.8
});
formattedString.Spans.Add(new Span
{
  Text = "Nullam feugiat sodales elit, et maximus nibh vulputate id.",
  LineHeight = 1.8
});
var label = new Label
{
  FormattedText = formattedString,
  LineBreakMode = LineBreakMode.WordWrap
};

The following screenshots show the result of setting the Span.LineHeight property to 1.8:

Styling labels

The previous sections covered setting Label and Span properties on a per-instance basis. However, sets of properties can be grouped into one style that is consistently applied to one or many views. This can increase readability of code and make design changes easier to implement. For more information, see Styles.