Reputation: 111
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;
Upvotes: 0
Views: 1777
Reputation: 14956
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 :
Upvotes: 3