Articles in this section
Category / Section

How to style Xamarin.Forms ListView using cascading style sheet (CSS)?

1 min read

You can style visual elements in ItemTemplate of Xamarin.Forms ListView using cascading style sheet (CSS). This KB article explains how to create CSS files, style CSS files, and load them in Xamarin.Forms applications.

Create CSS on Xamarin.Forms apps

  1. Create an empty stylesheet.css file by right-clicking your .NET Standard library project.
  2. Set the build action of CSS file to EmbeddedResource.

 Adding stylesheet

 

Style a CSS file

The Selectors are used to style the ContentPage elements in the CSS file. To learn more about Selectors and their types, refer to this documentation.

 

 
#listView 
{
    background-color: lightgray;
}
grid 
{
    margin: 20;
}
.bookName 
{
    font-style: bold;
    font-size: medium;
}
.bookDescription 
{
    margin-top: 15;
}
 

 

Load a CSS file in an application

A style sheet can be loaded and parsed with the StyleSheet class before being added to a ResourceDictionary. You can add a CSS file in your application as demonstrated in the following code sample.

 

<Application>
    <Application.Resources>
        <StyleSheet Source="/Assets/stylesheet.css" />
    </Application.Resources>
</Application>

 

Consume a Style sheet

Using defined selectors in your CSS file, you can apply the style to your ContentPage elements as demonstrated in the following code sample.

 

<ContentPage>
        <Grid>
            <Grid.RowDefinitions>
                <RowDefinition Height="*"/>
            </Grid.RowDefinitions>
            <sync:SfListView  AutoFitMode="Height" x:Name="listView"
                   ItemsSource="{Binding BookInfo}">
                <sync:SfListView.ItemTemplate>
                    <DataTemplate>
                        <Grid Padding="10">
                            <Grid.RowDefinitions>
                                <RowDefinition Height="0.4*" />
                                <RowDefinition Height="0.6*" />
                            </Grid.RowDefinitions>
                            <Label x:Name="label" Text="{Binding BookName}" StyleClass="bookName" />
                        <Label Grid.Row="1" Text="{Binding BookDescription}" StyleClass="bookDescription" />
                        </Grid>
                    </DataTemplate>
                </sync:SfListView.ItemTemplate>
            </sync:SfListView>
        </Grid>
</ContentPage>

 

Run the attached GitHub sample to render the following output.

ListViewItem with cascading style

 

Download the sample from GitHub.

Did you find this information helpful?
Yes
No
Help us improve this page
Please provide feedback or comments
Comments (0)
Please  to leave a comment
Access denied
Access denied