AgentRed
AgentRed

Reputation: 72

Xamarin.Forms how to Bind background color depending on conditions

how can you bind background color depending on status i tried this code and it didn't work

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

                }

and i binded the color to the .xaml

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

Upvotes: 2

Views: 3551

Answers (2)

Jason
Jason

Reputation: 89102

first, you can only bind to public properties

public Color BGColor { get; set; }

BindingContext = this;

then in your code, set that Property's value - you may also need to implement INPC on your class

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

            }

Upvotes: 1

MwBakker
MwBakker

Reputation: 495

You are changing this.BindingContext without an observer being called on. So the color changes, but the View does not get notified.

Add a 'set' to the color containing a RaisePropertyChanged, like below:

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

Now anytime color is being changed a trigger is being made to the View to update the state of the bound color.

Upvotes: 1

Related Questions