c# - Xamarin如果包含减号,我如何更改标签文本颜色
问题描述
所以我需要改变标签颜色,如果它有正或负平衡。
<Label x:Name="label" Text="$ -100"/>
我试过检查它是否包含减号。
if( label.Text.Contains("-"))
labe.TextColor = Color.Red;
else
label.TextColor = Color.Green;
解决方案
您可以使用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";
}
效果:
推荐阅读
- c - 从 scanf 切换到 fgets & Char 到 Int - 卡在 while statment
- python - python html.select 返回无
- node.js - 将 json 响应添加到 Map 字段 Mongoose 节点
- java - 如何将 Flux 或 Mono 发送到模板 (Freemaker)
- python - 更简化的计算文件行数的方法(python)
- python - Telegram Bot 无法使用 Webhook,程序正在运行但没有得到任何响应
- java - Java根据比率和人口规模添加对象
- java - 在 Eclipse IDE 上运行程序时,显示致命错误
- python - pytube 的 RegexMatchError
- javascript - 我想解决 javascript OOP 问题,但我的代码不完整