如何使Label显示带有不同颜色字母的FormattedString?

Est*_*bel 3 c# data-binding xaml xamarin xamarin.forms

我正在使用FormattedString在Xamarin.Forms上的Label上显示自定义文本.我想要实现的是改变一个或多个元素的颜色,例如:$$ $$.但即使我改变颜色,Label也会显示所有具有相同颜色的美元符号:$$$$

这是视图上的标签:

<Label Text="{Binding AveragePrice, StringFormat='{0}'}" HorizontalTextAlignment="Center" />
Run Code Online (Sandbox Code Playgroud)

这是绑定到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 }
            }
        };
    }
}
Run Code Online (Sandbox Code Playgroud)

为什么这段代码不会改变美元符号的颜色?我怎样才能实现呢?

Bil*_*iss 10

将AveragePrice绑定到FormattedText属性,并删除StringFormat.

<Label FormattedText="{Binding AveragePrice}" HorizontalTextAlignment="Center" />
Run Code Online (Sandbox Code Playgroud)


Raf*_*ael 9

由于某种原因,我无法应用此处提供的解决方案。

但是,如果您想使用 XAML 解决此问题,这对我有用:

<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>  
Run Code Online (Sandbox Code Playgroud)

摘自此来源:https://www.c-sharpcorner.com/article/xamarin-forms-text-app/