首页 > 解决方案 > Xamarin如果包含减号,我如何更改标签文本颜色

问题描述

所以我需要改变标签颜色,如果它有正或负平衡。

<Label x:Name="label" Text="$ -100"/>

我试过检查它是否包含减号。

if( label.Text.Contains("-"))
 labe.TextColor = Color.Red;
else
label.TextColor = Color.Green;

标签: c#xamarin

解决方案


您可以使用IValueConverter来实现这一点:

在这里我用一个按钮进行测试,当我单击按钮时,我将更改标签文本并更改其颜色。

创建 ColorConvert 类:

class ColorConvert : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        string s = (string)value;
        if (!string.IsNullOrEmpty(s))
        {
            if (s.Contains("-"))
            {
                return Color.Red;
            }
            else
            {
                return Color.Green;
            }
        }
        return Color.Green;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

然后在你的 xaml 中:</p>

<ContentPage.Resources>
    <ResourceDictionary>
        <local:ColorConvert x:Key="colorConvert" />
    </ResourceDictionary>
</ContentPage.Resources>

<StackLayout Orientation="Vertical">
    <Label x:Name="label1" Text="$ 100" TextColor="{Binding Source={x:Reference label1},Path=Text,Converter={StaticResource colorConvert}}">
    </Label>

    <Button Text="click" Clicked="Button_Clicked"></Button>
</StackLayout>

在 .xaml.cs 中:

private void Button_Clicked(object sender, EventArgs e)
    {
        label1.Text = "$ -100";
    }

效果:

在此处输入图像描述


推荐阅读