We use cookies to give you the best experience on our website. If you continue to browse, then you agree to our privacy policy and cookie policy. Image for the cookie policy date

Conditional Formatting

Can you show me how to conditionally change the background color of a card based on certain criteria?

For examble, a databound card layout that reads names. If the name is male I want the card to be blue. If it is female, I want the card to be pink.


1 Reply

RA Rachel A Syncfusion Team July 25, 2019 01:31 PM UTC

Hi Michael, 
We can achieve your requirement by changing the item template of the SfCardView based on the Rating property of the model using DataTemplateSelector. Please check the below code snippet and sample for your reference. 
public class CustomDataTemplateSelector : DataTemplateSelector
        public DataTemplate BlueBackgroundTemplate { getset; }
        public DataTemplate PinkBackgroundTemplate { getset; }

        protected override DataTemplate OnSelectTemplate(object item, BindableObject container)
            if (Convert.ToDouble(((CardData)item).Rating) <= 3)
                ((CardData)item).BlueBackgroundColor = Color.Blue;
                return BlueBackgroundTemplate;
                ((CardData)item).PinkBackgroundColor = Color.Pink;
                return PinkBackgroundTemplate;

            <DataTemplate x:Key="blueTemplate">
                <card:SfCardView BackgroundColor="{Binding BlueBackgroundColor}">
                    <local: CustomStackLayout />

            <DataTemplate x:Key="pinkTemplate">
                 <card:SfCardView BackgroundColor="{Binding PinkBackgroundColor}">
                    <local:CustomStackLayout />

            <local:CustomDataTemplateSelector x:Key="dataTemplateSelector"
                BlueBackgroundTemplate="{StaticResource blueTemplate}"
                PinkBackgroundTemplate="{StaticResource pinkTemplate}" />

 <card:SfCardLayout x:Name="cardLayout" BindableLayout.ItemsSource="{Binding Data}" BindableLayout.ItemTemplateSelector="{StaticResource dataTemplateSelector}" SwipeDirection="Left" VerticalOptions="Center"  HeightRequest="600" WidthRequest="300">
Also have attached the sample for your reference, please download it from the following location. 
Please let us know if you need further assistance on this. 

Live Chat Icon For mobile
Up arrow icon