MSDN Documentation

Labels in .NET MAUI

The Label control in .NET MAUI is used to display single or multi-line lines of text. It's a fundamental UI element for presenting information to the user.

Key Features and Properties

  • Text: The primary property to set the content of the label.
  • TextColor: Sets the color of the text.
  • FontSize: Specifies the size of the text.
  • FontAttributes: Allows setting text to bold, italic, or both.
  • HorizontalTextAlignment: Controls the horizontal alignment of the text within the label's bounds.
  • VerticalTextAlignment: Controls the vertical alignment of the text within the label's bounds.
  • MaxLines: Limits the number of lines the label can display.
  • LineBreakMode: Defines how text wraps or truncates when it exceeds the label's bounds (e.g., WordWrap, CharacterWrap, HeadTruncation).

Basic Usage

Here's a simple example of how to create and configure a Label in XAML:

<Label Text="Welcome to .NET MAUI!"
                       TextColor="#0078D4"
                       FontSize="24"
                       FontAttributes="Bold"
                       HorizontalTextAlignment="Center"
                       VerticalTextAlignment="Center" />

And in C#:

var myLabel = new Label
                {
                    Text = "Hello from C#!",
                    TextColor = Colors.Green,
                    FontSize = 18,
                    FontAttributes = FontAttributes.Italic,
                    HorizontalTextAlignment = TextAlignment.Start,
                    VerticalTextAlignment = TextAlignment.Center
                };

Styling Text

.NET MAUI provides extensive styling capabilities for Label. You can apply styles directly, use styles defined in resources, or leverage handlers for advanced customization.

Formatting with Spans

For more granular control over text formatting within a single label (e.g., different colors or styles for parts of the text), you can use the Spans collection.

Example with Spans

<Label>
    <Label.FormattedText>
        <FormattedString>
            <Span Text="This is " />
            <Span Text="styled"
                  TextColor="Blue"
                  FontAttributes="Bold" />
            <Span Text=" text!" />
        </FormattedString>
    </Label.FormattedText>
</Label>

This XAML will render:

This is styled text!

Accessibility

Ensure your labels are accessible by providing clear and concise text. For interactive elements, the label's text should describe its purpose. The SemanticProperties class can be used to enhance accessibility further.

<Label Text="Username" SemanticProperties.Hint="Enter your username" />

Next Steps

Explore how to integrate Label with other controls and layout options to create rich user interfaces. Consider using styles to maintain consistency across your application.