[英]Xamarin How can i change label text color if it contains minus
所以我需要改变 label 的颜色,如果它有正负平衡。
<Label x:Name="label" Text="$ -100"/>
我试过检查它是否包含减号。
if( label.Text.Contains("-"))
labe.TextColor = Color.Red;
else
label.TextColor = Color.Green;
您可以使用IValueConverter来实现这一点:
在这里,我用一个按钮进行测试,当我单击该按钮时,我将更改 label 文本并更改其颜色。
创建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();
}
}
然后在你的 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>
在.xaml.cs中:
private void Button_Clicked(object sender, EventArgs e)
{
label1.Text = "$ -100";
}
效果:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.