Xaml 根据数据绑定值设置背景颜色

Xaml 根据数据绑定值设置背景颜色,xaml,binding,xamarin,xamarin.forms,Xaml,Binding,Xamarin,Xamarin.forms,我以前见过一些答案,但没有什么真正帮助我 我还有一个类decidemel(这是从DB检索的数据集,但为了解决这个问题,我添加了一个ObservableCollection),其中包含 static DecideModel() { All = new ObservableCollection<DecideModel> { new DecideModel { DateP

我以前见过一些答案,但没有什么真正帮助我

我还有一个类
decidemel
(这是从DB检索的数据集,但为了解决这个问题,我添加了一个ObservableCollection),其中包含

static DecideModel()
    {
        All = new ObservableCollection<DecideModel>
        {
            new DecideModel
            {
                DatePerformed = new DateTime(2015, 4, 06),
                Result = "Maybe"
            },
            new DecideModel
            {
                DatePerformed = new DateTime(2015, 4, 05),
                Result = "No"
            },
            new DecideModel
            {
                DatePerformed = new DateTime(2015, 4, 04),
                Result = "Yes"
            }
        };
    }

    public DateTime DatePerformed { set; get; }

    public string  Result { set; get; }

    public static IList<DecideModel> All { set; get; }
}
static decidemel()
{
All=新的可观测集合
{
新分贝
{
DatePerformed=新的日期时间(2015年4月6日),
Result=“可能”
},
新分贝
{
DatePerformed=新的日期时间(2015年4月5日),
结果=“否”
},
新分贝
{
DatePerformed=新的日期时间(2015年4月4日),
结果=“是”
}
};
}
public DateTime DatePerformed{set;get;}
公共字符串结果{set;get;}
公共静态IList All{set;get;}
}
在我的XAML代码中

<ContentPage.Resources>
    <ResourceDictionary>
        <Color x:Key="Maybe">#ffddbc21</Color>
        <Color x:Key="Yes">#3CB371</Color>
        <Color x:Key="No">#B22222</Color>
        <Color x:Key="Depends">#ffd78800</Color>
    </ResourceDictionary>
</ContentPage.Resources>

<Label Text="{Binding Result}" HorizontalOptions="FillAndExpand" BackgroundColor="{StaticResource {BindingSource Result}}" />

#ffddbc21
#3CB371
#B22222
#ffd78800
我试图根据从对象获得的结果动态设置标签的背景色


如果你对如何做有任何想法,请告诉我。我正在寻找任何有用的选项。

您可能需要的是
值转换器。您现在要做的是将背景色设置为“可能”、“否”或“是”,这显然不是一种颜色

您需要做的是将该值转换为颜色。你可以这样做

创建一个实现
IValueConverter
接口的新类。它可能看起来像这样:

public class YesNoMaybeToColorConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
            switch(value.ToString().ToLower())
            {
                    case "yes":
                        return Color.Green;
                    case "no":
                        return Color.Red;
                    case "maybe":
                        return Color.Orange;
            }

            return Color.Gray;
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
            // You probably don't need this, this is used to convert the other way around
            // so from color to yes no or maybe
            throw new NotImplementedException();
    }
}
<ContentPage.Resources>
   <!-- Add this line below -->
   <local:YesNoToBooleanConverter x:Key="YesNoMaybeToColorConverter" />
   <!-- You can remove the underneath -->
    <!--<ResourceDictionary>
        <Color x:Key="Maybe">#ffddbc21</Color>
        <Color x:Key="Yes">#3CB371</Color>
        <Color x:Key="No">#B22222</Color>
        <Color x:Key="Depends">#ffd78800</Color>
    </ResourceDictionary>-->
</ContentPage.Resources>
<Label Text="{Binding Result}" HorizontalOptions="FillAndExpand" BackgroundColor="{Binding Result, Converter={StaticResource YesNoMaybeToColorConverter}}" />
然后将此类作为静态资源添加到XAML页面,如下所示:

public class YesNoMaybeToColorConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
            switch(value.ToString().ToLower())
            {
                    case "yes":
                        return Color.Green;
                    case "no":
                        return Color.Red;
                    case "maybe":
                        return Color.Orange;
            }

            return Color.Gray;
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
            // You probably don't need this, this is used to convert the other way around
            // so from color to yes no or maybe
            throw new NotImplementedException();
    }
}
<ContentPage.Resources>
   <!-- Add this line below -->
   <local:YesNoToBooleanConverter x:Key="YesNoMaybeToColorConverter" />
   <!-- You can remove the underneath -->
    <!--<ResourceDictionary>
        <Color x:Key="Maybe">#ffddbc21</Color>
        <Color x:Key="Yes">#3CB371</Color>
        <Color x:Key="No">#B22222</Color>
        <Color x:Key="Depends">#ffd78800</Color>
    </ResourceDictionary>-->
</ContentPage.Resources>
<Label Text="{Binding Result}" HorizontalOptions="FillAndExpand" BackgroundColor="{Binding Result, Converter={StaticResource YesNoMaybeToColorConverter}}" />

现在在你的绑定中,你必须告诉他使用什么转换器。这样做:

public class YesNoMaybeToColorConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
            switch(value.ToString().ToLower())
            {
                    case "yes":
                        return Color.Green;
                    case "no":
                        return Color.Red;
                    case "maybe":
                        return Color.Orange;
            }

            return Color.Gray;
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
            // You probably don't need this, this is used to convert the other way around
            // so from color to yes no or maybe
            throw new NotImplementedException();
    }
}
<ContentPage.Resources>
   <!-- Add this line below -->
   <local:YesNoToBooleanConverter x:Key="YesNoMaybeToColorConverter" />
   <!-- You can remove the underneath -->
    <!--<ResourceDictionary>
        <Color x:Key="Maybe">#ffddbc21</Color>
        <Color x:Key="Yes">#3CB371</Color>
        <Color x:Key="No">#B22222</Color>
        <Color x:Key="Depends">#ffd78800</Color>
    </ResourceDictionary>-->
</ContentPage.Resources>
<Label Text="{Binding Result}" HorizontalOptions="FillAndExpand" BackgroundColor="{Binding Result, Converter={StaticResource YesNoMaybeToColorConverter}}" />


它现在应该可以在
结果
字段中看到该值,将其通过您定义的转换器,并返回与该值对应的颜色。

我找到了另外两个管理该值的选项,因为有时我们不仅需要更改颜色,还需要更改字体和其他值。 首先,您需要向控件添加名称,如下所示:

public class YesNoMaybeToColorConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
            switch(value.ToString().ToLower())
            {
                    case "yes":
                        return Color.Green;
                    case "no":
                        return Color.Red;
                    case "maybe":
                        return Color.Orange;
            }

            return Color.Gray;
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
            // You probably don't need this, this is used to convert the other way around
            // so from color to yes no or maybe
            throw new NotImplementedException();
    }
}
<ContentPage.Resources>
   <!-- Add this line below -->
   <local:YesNoToBooleanConverter x:Key="YesNoMaybeToColorConverter" />
   <!-- You can remove the underneath -->
    <!--<ResourceDictionary>
        <Color x:Key="Maybe">#ffddbc21</Color>
        <Color x:Key="Yes">#3CB371</Color>
        <Color x:Key="No">#B22222</Color>
        <Color x:Key="Depends">#ffd78800</Color>
    </ResourceDictionary>-->
</ContentPage.Resources>
<Label Text="{Binding Result}" HorizontalOptions="FillAndExpand" BackgroundColor="{Binding Result, Converter={StaticResource YesNoMaybeToColorConverter}}" />

  • 您可以像这样在代码隐藏中设置颜色和其他属性,这种方式需要一些时间进行更新,所以当文本属性刚刚更新时,这不是最佳选择

    protected override void OnAppearing()
    {
        if (this.MyLabel.Text.Contains("yes")
                 {
            this.MyLabel.TextColor = Color.FromHex("#98ee99");
        }
        else
        {
            this.MyLabel.TextColor = Color.FromHex("#ff867c");
        }
    
    }

  • 另一种方法是使用Prism EventAggregator,我想在Xamarin.Forms中就是消息中心。这里有一个关于棱镜的好例子[

  • 在这种情况下,您应该从项目中的任何位置发送带有您的值的事件,例如,当它已经更新时

     _evenAggregator.GetEvent<MyEvent>().Publish(Result);
    
    \u evenAggregator.GetEvent().Publish(结果);
    
    然后,您应该在需要接收新值的地方订阅事件。在这种情况下,它应该是代码隐藏类中的一个appearing方法

     void UpdateColor(string result)
        {
         if(result.Contains("yes")
                {
                this.MyLabel.TextColor = Color.FromHex("#98ee99");
                }
                else
                {
                this.MyLabel.TextColor = Color.FromHex("#ff867c");
                }
        }
    
    
    
    
    
         protected override void OnAppearing()
            {
    base.OnAppearing();
          _eventAggregator.GetEvent<MyEvent>().Subscribe(UpdateColor);
            }
    
    void UpdateColor(字符串结果)
    {
    如果(结果包含(“是”)
    {
    this.MyLabel.TextColor=Color.FromHex(“#98ee99”);
    }
    其他的
    {
    this.MyLabel.TextColor=Color.FromHex(“#ff867c”);
    }
    }
    出现时受保护的覆盖无效()
    {
    base.OnAppearing();
    _eventAggregator.GetEvent().Subscribe(UpdateColor);
    }
    
    为了实现这一点而无需太多开销,您可以使用。请注意,您可以根据需要为每个触发器添加任意多的setter,使其比以前建议的解决方案稍微灵活一些,它还可以将视图逻辑保留在视图中应该保留的位置

    <Label Text="{Binding Result}" HorizontalOptions="FillAndExpand">
        <Label.Triggers>
            <DataTrigger TargetType="Label" Binding="{Binding Result}" Value="Yes">
                <Setter Property="BackgroundColor" Value="#3CB371" />
            </DataTrigger>
            <DataTrigger TargetType="Label" Binding="{Binding Result}" Value="No">
                <Setter Property="BackgroundColor" Value="#B22222" />
            </DataTrigger>
            <DataTrigger TargetType="Label" Binding="{Binding Result}" Value="Maybe">
                <Setter Property="BackgroundColor" Value="#ddbc21" />
            </DataTrigger>
            <DataTrigger TargetType="Label" Binding="{Binding Result}" Value="Depends">
                <Setter Property="BackgroundColor" Value="#d78800" />
            </DataTrigger>
        </Label.Triggers>
    </Label>
    
    
    
    请注意,您可以通过将
    BackgroundColor
    属性设置为合理的默认值(在本例中可能是“取决于”)来删除其中一个触发器