【问题标题】:Xamarin.Forms how to Bind background color depending on conditionsXamarin.Forms 如何根据条件绑定背景颜色
【发布时间】:2018-09-19 12:48:27
【问题描述】:

如何根据状态绑定背景颜色 我试过这段代码,它没有工作

var cat = JsonConvert.DeserializeObject<List<TableStat>>(response);
                for(int i = 0;i<cat.Count;i++)
                {
                    if (cat[i].table_status == "Available")
                    {
                        color = "Green";
                        this.BindingContext = color;
                    }
                    else if (cat[i].table_status == "Unavailable")
                    {
                        color = "Black";
                        this.BindingContext = color;
                    }

                }

我将颜色绑定到 .xaml

 <StackLayout HorizontalOptions="FillAndExpand"  BackgroundColor="{Binding color}">

【问题讨论】:

  • 你在使用 mvvm 吗?
  • 是的,我正在使用restapi来收集数据@Arvindraja
  • 你需要创建一个转换器来设置颜色取决于条件,你可以关注这个Answer
  • 解决方案在哪里?:

标签: c# android ios xaml xamarin


【解决方案1】:

首先,您只能绑定到公共属性

public Color BGColor { get; set; }

BindingContext = this;

然后在您的代码中,设置该属性的值 - 您可能还需要在您的类上实现 INPC

            for(int i = 0;i<cat.Count;i++)
            {
                if (cat[i].table_status == "Available")
                {
                    BGColor = Color.Green;
                }
                else if (cat[i].table_status == "Unavailable")
                {
                    BGColor = Color.Black;
                }

            }

【讨论】:

  • 应该在`InitializeComponent();`下面输入BindingContext = this
  • `BackgroundColor="{Binding BGColor}"`那么我会像这样绑定BGColor?
  • 你是否也在课堂上实施了 INPC?或者,您可以只显式设置 BackgroundColor 属性,而不是使用 Bindings
  • 什么是 INPC?我如何实现它?
  • INotifyPropertyChanged - 这已在之前的问题中向您解释过 - stackoverflow.com/questions/52231810/…
【解决方案2】:

您正在更改 this.BindingContext 而没有调用观察者。所以颜色发生了变化,但视图没有得到通知。

为包含 RaisePropertyChanged 的​​颜色添加一个“集合”,如下所示:

 set { color = value; 
         RaisePropertyChanged("Model");  //<- this should tell the view to update
     }

现在,只要更改颜色,就会对视图进行触发器以更新绑定颜色的状态。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-04-21
    • 2015-07-17
    • 2021-09-03
    • 2011-04-23
    • 1970-01-01
    • 1970-01-01
    • 2023-01-16
    • 2016-04-03
    相关资源
    最近更新 更多