Computer Magic Logo
Formatted text

Monday, April 11, 2016

Published by Aristotelis Pitaridis

The text property of the label does not allow us to display formatted text. This can be done by using the FormatedText property. This property is of type FormattedString which has a Spans property of type IList<Span> in order to store a list of Span objects. Each Span object can be formatted using the following six properties.

  • Text
  • FontFamily
  • FontSize
  • FontAttributes
  • ForegroundColor
  • BackgroundColor

Below we can see an example of using the FormatedText property.

FormattedString MyFormattedString = new FormattedString();

MyFormattedString.Spans.Add(new Span
{
    Text = "Hello ",
    FontAttributes = FontAttributes.Bold,
    ForegroundColor = Color.Red,
    BackgroundColor = Color.Yellow
});

MyFormattedString.Spans.Add(new Span
{
    Text = "world!",
    FontSize = Device.GetNamedSize(NamedSize.Large, typeof(Label)),
    FontAttributes = FontAttributes.Bold | FontAttributes.Italic,
    ForegroundColor = Color.White,
    BackgroundColor = Color.Blue
});

MyLabel.FormattedText = MyFormattedString;