This is a migrated thread and some comments may be shown as answers.

Changing the background color of the itemstyle dynamically

1 Answer 1167 Views
ListView
This is a migrated thread and some comments may be shown as answers.
FS
Top achievements
Rank 1
FS asked on 20 Jul 2016, 10:26 PM

Hi:

 

We just downloaded the Telerik Xamarin UI controls for evaluation.

We need to know the approach to change  the background color of an itemstyle based on a property in my custom object.  For example, if the Amount property of our object is less than 10 dollars, we want to set the backcolor in red.  If the Amount is greater than 10, we want to set it to a green backcolor.  

 

Thanks

 

David

1 Answer, 1 is accepted

Sort by
0
Lance | Manager Technical Support
Telerik team
answered on 22 Jul 2016, 06:12 PM
Hi David,

You can accomplish this with a Converter. As an example, imagine we have a list of cars, where a car is:

public class Car
{
    public string Make {get; set;}
    public double Price {get;set;}
}


That list of cars is bound to the ListView and we're using this ItemTemplate:

<DataTemplate>
              <listView:ListViewTemplateCell>
                <listView:ListViewTemplateCell.View>
                  <Grid BackgroundColor="{Binding Converter={StaticResource PriceColorConverter}}">
                        <Label Text="{Binding Make}" />
                  </Grid>
                </listView:ListViewTemplateCell.View>
              </listView:ListViewTemplateCell>
</DataTemplate>


The StaticResource PriceColorConverter is defined as:

<converters:PriceColorConverter x:Key="PriceColorConverter" />


The BackgroundColor binding passes the bound object to the converter, in which you return the appropriate color based of a property's value.

For example, I make the background Red if it's over 50,000 and Green otherwise.

public class PriceColorConverter : IValueConverter
{
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value == null)
                return null;
 
            var car = value as Car;
 
            if(car.Price > 50000)
               return Color.Red;
 
            return Color.Green;
       }
 
        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
}


Let us know if you have any further questions or concerns. Thank you for contacting Telerik Support and for choosing UI for Xamarin.

Regards,
Lance | Tech Support Engineer, Sr.
Telerik by Progress
Do you want to have your say when we set our development plans? Do you want to know when a feature you care about is added or when a bug fixed? Explore the Telerik Feedback Portal and vote to affect the priority of the items
Tags
ListView
Asked by
FS
Top achievements
Rank 1
Answers by
Lance | Manager Technical Support
Telerik team
Share this question
or