如何使标签显示具有不同颜色字母的格式化字符串?

8
我正在使用FormattedString在Xamarin.Forms的标签上显示自定义文本。我想要实现的是更改一个或多个元素的颜色,例如: $$$$. 但是,即使我更改了颜色,标签仍然只显示所有美元符号相同的颜色:$$$$。
这是视图上的标签:
<Label Text="{Binding AveragePrice, StringFormat='{0}'}" HorizontalTextAlignment="Center" />

以下是与ViewModel标签文本绑定的属性代码:
```

以下是与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 }
            }
        };
    }
}

为什么这段代码不能改变美元符号的颜色?我该怎样让它发生变化?

2
将AveragePrice绑定到FormattedText属性,并删除StringFormat。<Label FormattedText="{Binding AveragePrice}" HorizontalTextAlignment="Center" /> - Bill Reiss
很好!它起作用了。感谢@BillReiss。你应该发布答案,标记问题为已解决。 - Esteban Verbel
这段代码在一个简单的Label中可以工作。但是如果我将该Label加载到DataTemplate中,相同的代码就无法工作。有什么建议吗? - Divakar
@Divakar是ListView中的DataTemplate吗? - Esteban Verbel
@Divakar,问题在于您无法直接从ListView中引用ViewModel的属性,因为它具有项源属性(您绑定到ListView的集合)。您可以通过引用ViewModel的“根”来解决此问题。对于这种情况,您可以这样做:FormattedText = "{Binding Source = {x:Reference Name = theListViewName},Path = BindingContext.AveragePrice}"。 - Esteban Verbel
显示剩余3条评论
2个回答

14
将AveragePrice绑定到FormattedText属性,移除StringFormat。
<Label FormattedText="{Binding AveragePrice}" HorizontalTextAlignment="Center" />

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>  

以下翻译内容来自此来源


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接