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.


Thanks!


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. 
 
[C#] 
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;
            }
            else
            {
                ((CardData)item).PinkBackgroundColor = Color.Pink;
                return PinkBackgroundTemplate;
            }
        }
}
 
 
[XAML] 
<ContentPage.Resources>
        <ResourceDictionary>
 

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

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

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

        </ResourceDictionary>
    </ContentPage.Resources>
 
 
 <card:SfCardLayout x:Name="cardLayout" BindableLayout.ItemsSource="{Binding Data}" BindableLayout.ItemTemplateSelector="{StaticResource dataTemplateSelector}" SwipeDirection="Left" VerticalOptions="Center"  HeightRequest="600" WidthRequest="300">
 </card:SfCardLayout>  
 
 
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. 
 
Regards, 
Rachel.   


Loader.
Up arrow icon