【问题标题】:Xamarin How can i change label text color if it contains minusXamarin如果包含减号,我如何更改标签文本颜色
【发布时间】:2020-12-02 00:30:00
【问题描述】:

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

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

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

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

【问题讨论】:

  • 你怎么称呼这个代码。你为什么关心标签?只需在 xaml 中设置颜色
  • 您拥有的代码应该可以工作,或者如果您正在使用数据绑定,您可以使用 IValueConverter
  • 我的任务是在您启动应用程序时显示更改该标签的颜色,因此如果我们将其设置为 $ -100 以显示红色,如果是肯定的则显示绿色。我在初始化组件之后立即在公共 MainPage 中调用此方法。但它不适用于红色。

标签: c# xamarin


【解决方案1】:

您可以使用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中:

<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";
    }

效果:

【讨论】:

    猜你喜欢
    • 2019-01-28
    • 2020-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-11
    • 2013-09-12
    相关资源
    最近更新 更多