【问题标题】:Set background color depending on data-bound value根据数据绑定值设置背景颜色
【发布时间】:2015-07-17 17:00:22
【问题描述】:

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

我还有一个类DecideModel(这将是从数据库中检索到的数据集,但出于这个问题的目的,我添加了一个 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; }
}

在我的 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}}" />

我正在尝试根据我从对象获得的结果动态设置标签的背景颜色。

如果您对如何操作有任何想法,请告诉我。我正在寻找任何可用的有用选项。

【问题讨论】:

    标签: xaml binding xamarin xamarin.forms


    【解决方案1】:

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

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

    创建一个实现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();
        }
    }
    

    然后将此类作为静态资源添加到您的 XAML 页面,如下所示:

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

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

    【讨论】:

      【解决方案2】:

      对于无需太多开销即可实现此目的的纯 XAML 方法,您可以使用DataTrigger。请注意,您可以根据需要为每个触发器添加任意数量的设置器,这比之前建议的解决方案稍微灵活一些,它还将视图逻辑保留在视图中应有的位置。

      <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 属性设置为合理的默认值(在这种情况下可能是“依赖”)来删除其中一个触发器。

      【讨论】:

      • 这对我有帮助。我喜欢这个项目,因为它可以快速解决简单情况。谢谢。
      【解决方案3】:

      我找到了另外 2 个选项来管理它,因为有时我们不仅需要更改颜色,还需要更改字体和其他值。 首先,您需要像这样向控件添加名称:

      1. 你可以像这样在后面的代码中设置颜色和其他属性,这种方式需要一些时间来更新,所以当Text属性刚刚更新时,这不是最好的选择。

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

        }

      2. 另一种方法是使用 Prism EventAggregator,我猜在 Xamarin.Forms 中它是 Messaging Center。这是 Prism 的一个很好的例子 [https://codesandchips.wordpress.com/2017/03/30/xamarin-getting-started-with-prism-messaging/][1]

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

       _evenAggregator.GetEvent<MyEvent>().Publish(Result);
      

      然后,您应该在需要接收新价值的地方订阅事件。在这种情况下,它应该是类后面代码中的 OnAppearing 方法。

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

      【讨论】:

        猜你喜欢
        • 2011-12-27
        • 1970-01-01
        • 1970-01-01
        • 2021-07-09
        • 2015-04-21
        • 1970-01-01
        • 2012-10-20
        • 1970-01-01
        • 2013-04-30
        相关资源
        最近更新 更多