简体   繁体   中英

Xamarin How can i change label text color if it contains minus

So i need to change label color if it have positive or negative balance.

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

I've tried by checking does it contains minus.

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

You could use IValueConverter to achieve this:

Here i test wtih a button,when i click the button i will change the label text and change its color.

create ColorConvert class:

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();
    }
}

then in your xaml :

<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>

in the.xaml.cs:

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

the effect:

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM