Search code examples
c#listviewbindingxamarintextcolor

Label color property in listview xamarin


I would like to customize my list view to add some color depending on the label property.

If my amount label is > 0, I would like to set the color to green and if not to red.

How can I do that ?

        // Create the list view
        listView = new ListView
        {
            // Source of data items
            ItemsSource = items,

            // Define the template for displaying each item
            ItemTemplate = new DataTemplate(() =>
            {
                Label noLabel = new Label();
                noLabel.SetBinding(Label.TextProperty, "no");

                Label orderDateLabel = new Label();
                orderDateLabel.SetBinding(Label.TextProperty,
                    new Binding("orderDate") {Converter = new DateConverter()});

                Label customerNameLabel = new Label();
                customerNameLabel.SetBinding(Label.TextProperty, "customerName");

                Label externalDocumentNoLabel = new Label();
                externalDocumentNoLabel.SetBinding(Label.TextProperty, "externalDocumentNo");

                Label amountLabel = new Label();
                amountLabel.HorizontalTextAlignment = TextAlignment.End;

                // Binding with converter
                amountLabel.SetBinding(Label.TextProperty, new Binding("amount") {Converter = new AmountConverter()});

                // Return an assembled view cell
                return new ViewCell
                {
                    View = new Grid
                    {
                        // Fill the grid with data and position
                        Children =
                        {
                            {
                                noLabel, 0, 0
                            },
                            {
                                orderDateLabel, 1, 0
                            },
                            {
                                customerNameLabel, 2, 0
                            },
                            {
                                externalDocumentNoLabel, 3, 0
                            },
                            {
                                amountLabel, 4, 0
                            }
                        }
                    }
                };
            })
        };

If the amountLabel > 0 -> amoutLabel.TextColorProperty = Color.Green Else amountLabel.TextColorProperty = Color.Red

I know I had to play around with the TextColorProperty but how to retrieve the Text property of the label ?


Solution

  • You bind it to the same data element as the text property, and use a converter to convert the value to a Color.

    amountLabel.SetBinding(Label.TextColorProperty, new Binding("amount")
       { Converter = new AmountColorConverter() }
    );