How To Display Items In Card View Xamarin.Forms

Hi all, I hope you are doing good.

In this post, I am going to explaining how to display items in Card View using Xamarin.Forms.

Actually, CardView was introduced in Android 5.0 (Lollipop). But here, we are creating CardView for both, Android and iOS platforms using the “Frame” layout available in Xamarin.Forms.

In this post, I will take one scenario, that is, regarding eligibility for Vote.

  • If the person is 18 years old or less than 18, then the user is not eligible for Vote so we will label the user with red color on the card.
  • If the person is above 18, then he/she is eligible for Vote; so we will label the user with green color on the card.

Prerequisites

  1. Visual Studio for Windows or Mac.
  2. Java SDK, Android SDK, and Android NDK are for running the application in Android.
  3. If you want to run the application on iOS simulator, then Mac machine is mandatory.
  4. Need to have an idea about MVVM.

Step 1

Create Xamarin.Forms project in Visual Studio. In my case, I have created the project named “XFormsCardView”. After creating the project, the solution structure is as below.

Xamarin

 

Step 2

Create “ContentView” with the name "CardViewTemplate” under Xamarin.Forms PCL. We use this as an item template in the listview, so every item of listview renders based this ContentView. Place the following code inside your content view.

  1. <ContentView.Content>  
  2.     <Frame IsClippedToBounds="True"  
  3.            HasShadow="True"  
  4.            Padding="0"  
  5.            BackgroundColor="White" >  
  6.         <Frame.OutlineColor>  
  7.             <OnPlatform x:TypeArguments="Color"  
  8.                     Android="Gray"  
  9.                     iOS="Gray"/>  
  10.         </Frame.OutlineColor>  
  11.         <Frame.Margin>  
  12.             <OnPlatform x:TypeArguments="Thickness"  
  13.                      Android="10"   
  14.                      iOS="10"/>  
  15.         </Frame.Margin>  
  16.         <StackLayout Orientation="Horizontal">  
  17.             <BoxView Color="{Binding HasVote}" WidthRequest="6"/>  
  18.             <Grid VerticalOptions="CenterAndExpand"  
  19.                  Padding="0"  
  20.                  HorizontalOptions="FillAndExpand"  
  21.                  BackgroundColor="Transparent">  
  22.                 <Grid.RowDefinitions>  
  23.                     <RowDefinition Height="*"/>  
  24.                     <RowDefinition Height="Auto"/>  
  25.                     <RowDefinition Height="*"/>  
  26.                 </Grid.RowDefinitions>  
  27.                 <Label FontAttributes="Bold"  
  28.                    Grid.Row="0"  
  29.                    HorizontalTextAlignment="Start"  
  30.                    VerticalTextAlignment="Center"  
  31.                    FontSize="16"  
  32.                    Text="{Binding Name, Mode = TwoWay}">  
  33.                     <Label.LineBreakMode>  
  34.                         <OnPlatform x:TypeArguments="LineBreakMode"  
  35.                           Android="NoWrap"   
  36.                           iOS="TailTruncation"/>  
  37.                     </Label.LineBreakMode>  
  38.                 </Label>  
  39.                 <BoxView Grid.Row="1" Color="Gray"  
  40.                     HorizontalOptions="FillAndExpand"  
  41.                     HeightRequest="1"/>  
  42.                 <Grid Grid.Row="2"  
  43.                    BackgroundColor="Transparent"  
  44.                    Padding="4">  
  45.                     <Grid.ColumnDefinitions>  
  46.                         <ColumnDefinition Width="Auto" />  
  47.                         <ColumnDefinition />  
  48.                     </Grid.ColumnDefinitions>  
  49.                     <Label Grid.Row="0"  
  50.                           Grid.Column="0"  
  51.                           Text="User Age"/>  
  52.                     <Label Grid.Row="0"  
  53.                           Grid.Column="1"  
  54.                           Text="{Binding Age, Mode = TwoWay}"/>  
  55.                 </Grid>  
  56.             </Grid>  
  57.         </StackLayout>  
  58.     </Frame>  
  59. </ContentView.Content>  

Step 3

Create a Content page with the name “MainPage” under Xamarin.Forms PCL. Place the following code inside the Content Page.

  1. <StackLayout Orientation="Vertical">  
  2.         <Label Text="CardView Demo in Xamarin Forms"  
  3.                FontAttributes="Bold"  
  4.                FontSize="Medium"  
  5.                VerticalOptions="Start"  
  6.                HorizontalTextAlignment="Center"  
  7.                VerticalTextAlignment="Center"  
  8.                BackgroundColor="Transparent"  
  9.                HorizontalOptions="CenterAndExpand" />  
  10.         <ListView x:Name="listView"   
  11.                   SelectedItem="{Binding SelcetedItem,Mode=TwoWay}"   
  12.                   HasUnevenRows="True"  
  13.                   ItemsSource="{Binding lstUsers}" >  
  14.             <ListView.ItemTemplate>  
  15.                 <DataTemplate>  
  16.                     <ViewCell>  
  17.                         <local:CardViewTemplate/>  
  18.                     </ViewCell>  
  19.                 </DataTemplate>  
  20.             </ListView.ItemTemplate>  
  21.         </ListView>  
  22.     </StackLayout>  

If you observe the above code, I have added the above created “CardViewTemplate” as a viewcell for the listview. If you want to use that inside of Content Page, you have to add the following line Content Page.

  1. xmlns:local="clr-namespace:XFormsCardView"     

 In the above line, XFormsCardView is my namespace name of “CardViewTemplate”, so please change it to appropriate namespace based on your project.

Step 4

Create a class with the name “User” with some properties in Xamarin.Forms PCL like below.

  1. public class User  
  2.     {  
  3.         public string Name { get; set; }  
  4.         public int Age { get; set; }  
  5.   
  6.         // I assume if color is   
  7.         // Green, then user has vote  
  8.         // Red, then user is below 18  
  9.         public Color HasVote { get; set; }  
  10.     }  

Step 5

Create a class with the name “UserViewModel” with the following in Xamarin.Forms PCL.

  1. public class UserViewModel  
  2.     {  
  3.         public IList<User> lstUsers { get; set; }  
  4.         public object SelectedItem { get; set; }  
  5.         public UserViewModel()  
  6.         {  
  7.             lstUsers = new List<User>();  
  8.             GenerateCardModel();  
  9.         }  
  10.   
  11.         private void GenerateCardModel()  
  12.         {  
  13.             string[] arrNames = {  
  14.                 "David""John""Paul""Mark""James",  
  15.                 "Andrew""Scott""Steven""Robert""Stephen",  
  16.                 "William""Craig""Michael""Stuart""Christopher",  
  17.                 "Alan""Colin""Brian""Kevin"  
  18.             };  
  19.   
  20.             Random rnd = new Random();  
  21.   
  22.             for (var i = 0; i < arrNames.Length; i++)  
  23.             {  
  24.                 var age = rnd.Next(10, 30);  
  25.                 var user = new User()  
  26.                 {  
  27.                     Name = arrNames[i],  
  28.                     Age = age,  
  29.                     HasVote = age % 2 == 0 ? Color.Green : Color.Red,  
  30.                 };  
  31.                 lstUsers.Add(user);  
  32.             }  
  33.         }  
  34.     }  

Step 6

Place the following code in the code behind of “MainPage”. This is the place where we have to bind ViewModel with BindingContext.

  1. public partial class MainPage : ContentPage  
  2.     {  
  3.         public MainPage()  
  4.         {    
  5.             InitializeComponent();  
  6.                     this.BindingContext = new UserViewModel();  
  7.             }  
  8.     }  

Step 7

Now, you can run your application by setting required platform as a startup. Here, in my case, I’m running the application in Android and the outcome will be as below.

In the following image, the persons who are having a green label are eligible for Vote while the others are not eligible.

For full code, please visit here.

 

Xamarin

 

I hope you enjoyed reading this article. Please reach out to me through comments.


Similar Articles