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:

Labels with Text Decorations

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:

Label TextColor Example

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:

Label MaxLines Example

Formatted text

Labels expose a FormattedText property that 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.

Note

The BackgroundColor, Text, and Text bindable properties have a default binding mode of OneWay. For more information about this binding mode, see The Default Binding Mode in the Binding Mode guide.

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:

Label FormattedText Example

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:

Label LineHeight Example

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:

Span LineHeight Example

The text displayed by Label and Span instances can be turned into hyperlinks with the following approach:

  1. Set the TextColor and TextDecoration properties of the Label or Span.
  2. Add a TapGestureRecognizer to the GestureRecognizers collection of the Label or Span, whose Command property binds to a ICommand, and whose CommandParameter property contains the URL to open.
  3. Define the ICommand that will be executed by the TapGestureRecognizer.
  4. Write the code that will be executed by the ICommand.

The following code example, taken from the Hyperlink Demos sample, shows a Label whose content is set from multiple Span instances:

<Label>
    <Label.FormattedText>
        <FormattedString>
            <Span Text="Alternatively, click " />
            <Span Text="here"
                  TextColor="Blue"
                  TextDecorations="Underline">
                <Span.GestureRecognizers>
                    <TapGestureRecognizer Command="{Binding TapCommand}"
                                          CommandParameter="https://docs.microsoft.com/xamarin/" />
                </Span.GestureRecognizers>
            </Span>
            <Span Text=" to view Xamarin documentation." />
        </FormattedString>
    </Label.FormattedText>
</Label>

In this example, the first and third Span instances comprise text, while the second Span represents a tappable hyperlink. It has its text color set to blue, and has an underline text decoration. This creates the appearance of a hyperlink, as shown in the following screenshots:

Hyperlinks

When the hyperlink is tapped, the TapGestureRecognizer will respond by executing the ICommand defined by its Command property. In addition, the URL specified by the CommandParameter property will be passed to the ICommand as a parameter.

The code-behind for the XAML page contains the TapCommand implementation:

public partial class MainPage : ContentPage
{
    public ICommand TapCommand => new Command<string>(OpenBrowser);

    public MainPage()
    {
        InitializeComponent();
        BindingContext = this;
    }

    void OpenBrowser(string url)
    {
        Device.OpenUri(new Uri(url));
    }
}

The TapCommand executes the OpenBrowser method, passing the TapGestureRecognizer.CommandParameter property value as a parameter. In turn, this method calls the Device.OpenUri method to open the URL in a web browser. Therefore, the overall effect is that when the hyperlink is tapped on the page, a web browser appears and the URL associated with the hyperlink is navigated to.

The previous approach to creating a hyperlink requires writing repetitive code every time you require a hyperlink in your application. However, both the Label and Span classes can be subclassed to create HyperlinkLabel and HyperlinkSpan classes, with the gesture recognizer and text formatting code added there.

The following code example, taken from the Hyperlink Demos sample, shows a HyperlinkSpan class:

public class HyperlinkSpan : Span
{
    public static readonly BindableProperty UrlProperty =
        BindableProperty.Create(nameof(Url), typeof(string), typeof(HyperlinkSpan), null);

    public string Url
    {
        get { return (string)GetValue(UrlProperty); }
        set { SetValue(UrlProperty, value); }
    }

    public HyperlinkSpan()
    {
        TextDecorations = TextDecorations.Underline;
        TextColor = Color.Blue;
        GestureRecognizers.Add(new TapGestureRecognizer
        {
            Command = new Command(() => Device.OpenUri(new Uri(Url)))
        });
    }
}

The HyperlinkSpan class defines a Url property, and associated BindableProperty, and the constructor sets the hyperlink appearance and the TapGestureRecognizer that will respond when the hyperlink is tapped. When a HyperlinkSpan is tapped, the TapGestureRecognizer will respond by executing the Device.OpenUri method to open the URL, specified by the Url property, in a web browser.

The HyperlinkSpan class can be consumed by adding an instance of the class to the XAML:

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:local="clr-namespace:HyperlinkDemo"
             x:Class="HyperlinkDemo.MainPage">
    <StackLayout>
        ...
        <Label>
            <Label.FormattedText>
                <FormattedString>
                    <Span Text="Alternatively, click " />
                    <local:HyperlinkSpan Text="here"
                                         Url="https://docs.microsoft.com/appcenter/" />
                    <Span Text=" to view AppCenter documentation." />
                </FormattedString>
            </Label.FormattedText>
        </Label>
    </StackLayout>
</ContentPage>

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.