Category / Section
How to add cards to the ListView in Xamarin.Forms
1 min read
It is a common use case to show the cards in a Xamarin.Forms.ListView. So that UI will be clean, and we need not worry about the memory usage, as the ListView by default handles the UI virtualization. This section describes how to bind a SfCardView instance for each row in the list.
Consider showing a list of social media applications as cards in a Xamarin.Forms application as below.
|
[XAML]
xmlns:cards="clr-namespace:Syncfusion.XForms.Cards;assembly=Syncfusion.Cards.XForms"
..
<!-- Binding the View Model -->
<ContentPage.BindingContext>
<viewmodel:SocialMediaAppViewModel />
</ContentPage.BindingContext>
<!-- ListView as parent layout -->
<ListView
x:Name="EventListView"
ItemsSource="{Binding Items}"
RowHeight="100"
SeparatorVisibility="None">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<!-- CardView as its DataTemplate -->
<cards:SfCardView Margin="10">
<Grid HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand">
<StackLayout Orientation="Horizontal">
<Image
Margin="10,0,0,0"
HeightRequest="40"
Source="{Binding Image}"
WidthRequest="40" />
<Label
Margin="10,0,0,0"
FontAttributes="Bold"
FontSize="16"
HorizontalOptions="Start"
LineBreakMode="NoWrap"
MaxLines="1"
Text="{Binding Title}"
TextColor="Black"
VerticalOptions="Center" />
</StackLayout>
</Grid>
</cards:SfCardView>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
[C#]
public class SocialMediaAppModel
{
public string Title {get; set;}
public string Image {get; set;}
}
[C#]
public class SocialMediaAppViewModel
{
public IEnumerable< SocialMediaAppModel > Items { get; set; }
public SocialMediaAppViewModel ()
{
Items = new SocialMediaAppModel []
{
new SocialMediaAppModel (){ Title = "Facebook" , Image = "FacebookFill.png"},
new SocialMediaAppModel (){ Title = "Gmail" , Image = "GmailFill.png"},
new SocialMediaAppModel (){ Title = "Instagram" , Image = "InstagramFill.png"},
new SocialMediaAppModel (){ Title = "WhatsApp" , Image = "WhatsappFill.png"},
};
}
}
You can get the complete sample from this Gitlab location.
