| MAUI-SearchBar | MAUI Introduction | |
.NET MAUI Span and FormattedString |
In .NET MAUI, Span and FormattedString are used together within a Label control to display text with multiple styles—such as different colors, fonts, or sizes—within a single string.
Span and FormattedString in .NET MAUI — they’re what you use when you want rich text formatting inside a single Label.
Span: Represents a segment of text with its own style (font, color, attributes).
FormattedString: A collection of Span objects that together form the text displayed in a Label.
This allows you to mix different styles (bold, italic, colors, sizes) in one label without needing multiple labels.
Basic FormattedString
<Label>
<Label.FormattedText>
<FormattedString>
<Span Text="Hello " FontSize="20" TextColor="Black"/>
<Span Text="Shivshanker" FontAttributes="Bold" TextColor="DarkRed"/>
<Span Text=", welcome to MAUI!" FontSize="20" TextColor="DarkBlue"/>
</FormattedString>
</Label.FormattedText>
</Label>
👉 Output:
Binding Example
<Label>
<Label.FormattedText>
<FormattedString>
<Span Text="{Binding FirstName}" FontAttributes="Bold"/>
<Span Text=" "/>
<Span Text="{Binding LastName}" TextColor="Gray"/>
</FormattedString>
</Label.FormattedText>
</Label>
👉 Useful for showing names with different styles dynamically.
Span + FormattedString let you create rich, styled text inside a single Label — perfect for highlighting, mixing styles, and binding dynamic values.
FormattedString: A container class that holds a collection of Span objects. It is assigned to the FormattedText property of a Label.
Span: An individual segment of text that carries its own unique styling. By using multiple spans, you can create complex strings like "This is bold and italic" without using multiple Label controls.
Each Span can be independently styled using properties similar to a standard Label:
A significant advantage of using Span is that it supports GestureRecognizers. This allows you to add specific actions—like a TapGestureRecognizer—to just one part of the text, effectively creating inline hyperlinks within a paragraph.
<Label>
<Label.FormattedText>
<FormattedString>
<Span Text="By clicking, you agree to our " />
<Span Text="Terms of Service"
TextColor="Blue"
TextDecorations="Underline">
<Span.GestureRecognizers>
<TapGestureRecognizer Command="{Binding OpenTermsCommand}" />
</Span.GestureRecognizers>
</Span>
</FormattedString>
</Label.FormattedText>
</Label>
Use code with caution.
| MAUI-SearchBar | MAUI Introduction | |