This is the fifth article in the recently started series titled Developer Tips, which offers concise hints to enhance productivity. All the articles in this series can be accessed from here.
A label in .NET MAUI is a simple yet powerful View that presents read-only text, like titles, captions, or descriptions.
The Text property holds the string to be displayed and is also bindable.
Text can be formatted in various ways, including changing fonts, applying color, text transforms, or using bold, italic, or a combination of both.
Indeed, the true strength of the Label is in its FormattedText property. Consider it akin to an interpolated string in C#.
When you need to apply a series of formatting to a text, such as a hyperlink within a string, opt for FormattedText instead of using a Layout with multiple labels.
Internally, FormattedText is of type FormattedString, which holds a list of Spans, each of which can be individually formatted. An additional benefit is that Span also supports gestures.
In XAML:
<Label HorizontalOptions="Center" VerticalOptions="Center">
<Label.FormattedText>
<FormattedString>
<Span Text="This is a " />
<Span FontAttributes="Bold" Text="bold" />
<Span Text=", " />
<Span FontAttributes="Italic" Text="italic" />
<Span Text=", and " />
<Span
Text="hyperlinked"
TextColor="Blue"
TextDecorations="Underline">
<Span.GestureRecognizers>
<TapGestureRecognizer Tapped="OnTapped" />
</Span.GestureRecognizers>
</Span>
<Span Text=" text in a single label." />
</FormattedString>
</Label.FormattedText>
</Label>
In C#:
new Label()
{
FormattedText = new FormattedString()
{
Spans =
{
new Span().Text("This is a "),
new Span().Text("bold").Bold(),
new Span().Text(", "),
new Span().Text("italic").Italic(),
new Span().Text(", and "),
new Span()
{
TextColor = Colors.Blue,
TextDecorations = TextDecorations.Underline,
GestureRecognizers =
{
new TapGestureRecognizer().Invoke(x => x.Tapped += OnTapped),
},
}.Text("hyperlinked"),
new Span().Text(" text in a single label."),
},
},
}.Center()
The Markup package includes a FormattedText() extension method that accepts an array of Spans as input.
// Using C# 12 Collection Expression to simplify things
new Label().FormattedText([
new Span().Text("The word "),
new Span().Text("bold").Bold(),
new Span().Text(" is formatted.")
])
In conclusion, the use of Label’s FormattedText can reduce the nesting of UI elements, which decreases memory usage and, as a result, improves the app’s performance.
Further references:
- Label – Use formatted text
- Customizing your labels with FormattedText (YouTube video)
If you would like to recognize the work, kindly consider sponsoring on the GitHub Sponsor page or Buy Me a Coffee page. Thanks in advance.
Happy coding. Stay connected as we continue to learn and share the experiences from this exciting journey of being a .NET developer.