8

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?

8
  • 2
    Bind AveragePrice to the FormattedText property, and remove the StringFormat. <Label FormattedText="{Binding AveragePrice}" HorizontalTextAlignment="Center" />
    – Bill Reiss
    Feb 5, 2017 at 21:10
  • Great! it worked. Thanks @BillReiss. You should post the answer, to mark the question as answered Feb 5, 2017 at 21:27
  • ts working in a simple Label.But the same code not working if I load that Label inside a DataTemplate. Any advice?
    – Divakar
    Feb 7, 2017 at 13:42
  • @Divakar is the DataTemplate inside a ListView? Feb 7, 2017 at 18:47
  • @EstebanVerbel Yes. I have used DataTemplate inside a ListView
    – Divakar
    Feb 8, 2017 at 22:41

2 Answers 2

14

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

<Label FormattedText="{Binding AveragePrice}" HorizontalTextAlignment="Center" />
9

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/

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.