Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a Label display a FormattedString with letters of different color?

I am using a FormattedString to Display a customized text on a Label on Xamarin.Forms. What I am trying to achieve is to change the color of one or more of the elements, for example: $$$$. But even though I am changing the color the Label just displays all the dollar symbols with the same color: $$$$

This is the Label on the view:

<Label Text="{Binding AveragePrice, StringFormat='{0}'}" HorizontalTextAlignment="Center" />

And this is the code of the property bound to the label text on the ViewModel

public FormattedString AveragePrice
{
    get
    {
        return new FormattedString
        {
            Spans =
            {
                new Span { Text = "$", ForegroundColor=Color.Black },
                new Span { Text = "$", ForegroundColor=Color.Black },
                new Span { Text = "$", ForegroundColor=Color.Gray },
                new Span { Text = "$", ForegroundColor=Color.Gray }
            }
        };
    }
}

Why this code doesn't change the color of the dollar symbols? How can I make it happen?

like image 412
Esteban Verbel Avatar asked Feb 05 '17 20:02

Esteban Verbel


2 Answers

Bind AveragePrice to the FormattedText property, and remove the StringFormat.

<Label FormattedText="{Binding AveragePrice}" HorizontalTextAlignment="Center" />
like image 108
Bill Reiss Avatar answered Nov 19 '22 03:11

Bill Reiss


For some reason, I couln't apply the solutions presented here.

However, if you want to solve this with XAML, this worked for me:

<Label>  
    <Label.FormattedText>  
        <FormattedString>  
            <Span Text="Red color Bold" ForegroundColor="Red" FontAttributes="Bold"/>  
            <Span Text="$" TextColor="Black"/>  
            <Span Text="$" TextColor="Black"/>  
            <Span Text="$" TextColor="Grey"/>  
            <Span Text="$" TextColor="Grey"/>  
        </FormattedString>  
    </Label.FormattedText>  
</Label>  

Taken from this source: https://www.c-sharpcorner.com/article/xamarin-forms-text-app/

like image 33
Rafael Avatar answered Nov 19 '22 01:11

Rafael