Forum Xamarin.Forms

listView: change color of one item if statement is true

ganesh96ganesh96 Member ✭✭✭

Hi,

I have a listView with the following content:

xaml:

xaml.cs:

As you can see: the list consists of 5 items, all which have the color black (see .xaml).

I will add an if-statement soon. When this statement returns 'true', the color of Text4 only should turn to the color Red, overwriting the color black.
So the result would then be a list with Text1, Text2, Text3 and Text5 in the color Black, and Text4 in the color Red.

How can I achieve this?

Regards, Ganesh

Best Answers

Answers

  • JohnHJohnH GBMember ✭✭✭✭✭

    ItemsSource should be populated with a list of models instead of strings, the model contains a property that you can bind to to set the colour to black or red as per your logic.

  • ganesh96ganesh96 Member ✭✭✭

    Thanks for the response.

    I'm very new to data binding and I don't know (yet) how to implement it. I saw this Documentation https://docs.microsoft.com/en-us/xamarin/xamarin-forms/user-interface/listview/data-and-databinding , but I'm still having difficulties with it.

    Are you able to help me a bit?

    Regards, Ganesh

  • joergscjoergsc Member ✭✭

    In XAML define a resource like::

    Then

    <Label Text= "{Binding .}" TextColor="{Binding ., Converter={StaticResource TextToColorConverter}}

    And you need a Converter like:
    public class TextToColorConverter :IValueConverter
    {
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
    switch ((string)value)
    {
    case "Text4":
    return Color.Red;
    break;

                default:
                    return Color.Black;
            }
    
        }
    
  • joergscjoergsc Member ✭✭
    edited May 3

    The resource definition went missing...
    local:StatusToColorConverter x:Key="StatusToColorConverter"

  • ganesh96ganesh96 Member ✭✭✭

    Hi ColeX,

    Thanks for the answer, it seems to work except my listView displays something strange. My Page is located in the folder Pages and my Model is located in the folder Utils.Models:

    This is the result in my list with your exact code:

    Do you know what's the problem here?

    Regards, Ganesh

  • ganesh96ganesh96 Member ✭✭✭

    Thanks a lot!

Sign In or Register to comment.