How To Change ListView SelectedItem Bg Color In Xamarin.Forms

Introduction

This article describes how we can change ListView SelectedItem bg color in Xamarin.Forms. Sometimes we may need to set a different bg color for ListView selected item, so in this article, we will learn how to achieve this functionality using CustomRenderer.

Requirements

  • This article's source code is prepared by using Visual Studio 2017. And it is better to install the latest Visual Studio updates from here.
  • This article is prepared on a MAC machine.
  • This sample project is Xamarin.Forms.Net standard project.
  • This sample app is targeted for Android, iOS. And tested for Android & iOS.

Description

The creation of a Xamarin.Forms project is very simple in Visual Studio for Mac. It will create three projects

  1. Shared Code
  2. Xamarin.Android
  3. Xamarin.iOS

Because Mac system with Visual Studio for Mac doesn't support Windows projects (UWP, Windows, Windows Phone) the following steps will show you how to create Xamarin.Forms project in Mac system with Visual Studio.

First, open the Visual Studio for Mac. And Click on New Project

How To Change ListView SelectedItem Bg Color In Xamarin.Forms 

After that, we need to select whether you're doing Xamarin.Forms or Xamarin.Android or Xamarin.iOS project. if we want to create Xamarin.Forms project just follow the below screenshot.

How To Change ListView SelectedItem Bg Color In Xamarin.Forms 

Give the App Name i.e ListViewDemo.

How To Change ListView SelectedItem Bg Color In Xamarin.Forms 

Note
In the above screen under Shared Code, select use .NET Standard or Use Shared Library. Then click on Next Button and the below screenshot will show you how to browse to save the project on our PC.

How To Change ListView SelectedItem Bg Color In Xamarin.Forms 

After clicking on the Create button it will create the ListViewDemo Xamarin.Forms project like below

  • ListViewDemo: It is for Shared Code
  • ListViewDemo.Droid: It is for Android.
  • ListViewDemo.iOS: It is for iOS

How To Change ListView SelectedItem Bg Color In Xamarin.Forms 

We need to follow the below steps to change the selected-item background color for ListView.

.Net Standard/PCL:

Step 1:

Create your own Xaml page name is ListViewPage.xaml, and make sure to refer to "CustomViewCell" class in Xaml by declaring a namespace for its location and using the namespace prefix on the control element. The following code example shows how the "CustomViewCell" renderer class can be consumed by a XAML page:

And here we are trying to set the background color for ListView selected-item.

ListViewPage.xaml

  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <ContentPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" xmlns:custom="clr-namespace:ListViewDemo.CustomControls;assembly=ListViewDemo" xmlns:ios="clr-namespace:Xamarin.Forms.PlatformConfiguration.iOSSpecific;assembly=Xamarin.Forms.Core" BackgroundColor="White" x:Class="ListViewDemo.Views.ListViewPage">  
  3.     <ContentPage.Padding>  
  4.         <OnPlatform x:TypeArguments="Thickness" Android="0, 0, 0, 0" WinPhone="0, 0, 0, 0" iOS="0, 20, 0, 0" />  
  5.     </ContentPage.Padding>  
  6.     <ContentPage.Content>  
  7.         <StackLayout Padding="30,40,30,0" Spacing="50" BackgroundColor="White" VerticalOptions="FillAndExpand" HorizontalOptions="FillAndExpand">  
  8.             <Label Text="ListView SelectedItemColor" HorizontalOptions="CenterAndExpand" FontSize="20" TextColor="Maroon" FontAttributes="Bold" />  
  9.             <ListView Grid.Row="1" ItemsSource="{Binding OrdersList}" Footer="" ios:ListView.SeparatorStyle="FullWidth" HeightRequest="140" SeparatorColor="Gray">  
  10.                 <ListView.ItemTemplate>  
  11.                     <DataTemplate>  
  12.                         <custom:CustomViewCell SelectedItemBackgroundColor="#ADF3BE">  
  13.                             <ViewCell.View>  
  14.                                 <StackLayout Orientation="Horizontal">  
  15.                                     <Label Text="{Binding OrderType}" VerticalOptions="CenterAndExpand" FontSize="Medium" Font="15" TextColor="Gray" HorizontalOptions="StartAndExpand" />  
  16.                                     <StackLayout HorizontalOptions="EndAndExpand" Orientation="Horizontal" Spacing="15">  
  17.                                         <Frame OutlineColor="Green" HasShadow="false" Margin="0,8,0,8" BackgroundColor="Transparent" Padding="5">  
  18.                                             <Label Text="{Binding TotalCount}" HorizontalOptions="CenterAndExpand" VerticalOptions="CenterAndExpand" FontSize="10" TextColor="Red" />  
  19.                                         </Frame>  
  20.                                         <Image Source="back_icon.png" VerticalOptions="CenterAndExpand" HeightRequest="16" WidthRequest="16" HorizontalOptions="EndAndExpand" />  
  21.                                     </StackLayout>  
  22.                                 </StackLayout>  
  23.                             </ViewCell.View>  
  24.                         </custom:CustomViewCell>  
  25.                     </DataTemplate>  
  26.                 </ListView.ItemTemplate>  
  27.             </ListView>  
  28.         </StackLayout>  
  29.     </ContentPage.Content>  
  30. </ContentPage>  

Note:
The "custom" namespace prefix can be named anything. However, the clr-namespace and assembly values must match the details of the custom renderer class. Once the namespace is declared the prefix is used to reference the custom control/layout.

Make BindingContaxt in Code behind with ListViewPageViewmodel

ListViewPage.xaml.cs

  1. using ListViewDemo.ViewModels;  
  2. using Xamarin.Forms;  
  3. namespace ListViewDemoViews {  
  4.     public partial class ListViewPage: ContentPage {  
  5.         public ListViewPage() {  
  6.             InitializeComponent();  
  7.             BindingContext = new ListViewPageViewModel();  
  8.         }  
  9.     }  
  10. }  

ViewModels:

ListViewPageviewModel.cs
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Collections.ObjectModel;  
  4. using System.ComponentModel;  
  5. using System.Runtime.CompilerServices;  
  6. using ListViewDemo.Models;  
  7. namespace ListViewDemo.ViewModels {  
  8.     public class ListViewPageViewModel: INotifyPropertyChanged {  
  9.         ObservableCollection<Order> _ordersList;  
  10.         public ObservableCollection<Order> OrdersList {  
  11.             get {  
  12.                 return _ordersList;  
  13.             }  
  14.             set {  
  15.                 _ordersList = value;  
  16.                 OnPropertyChanged("OrdersList");  
  17.             }  
  18.         }  
  19.         protectedbool SetProperty < T > (ref T backingStore, T value,  
  20.             [CallerMemberName] string propertyName = "", Action onChanged = null) {  
  21.             if (EqualityComparer < T > .Default.Equals(backingStore, value)) returnfalse;  
  22.             backingStore = value;  
  23.             onChanged ? .Invoke();  
  24.             OnPropertyChanged(propertyName);  
  25.             returntrue;  
  26.         }  
  27.         //INotifyPropertyChanged implementation method  
  28.         publicevent PropertyChangedEventHandler PropertyChanged;  
  29.         protectedvoid OnPropertyChanged([CallerMemberName] string propertyName = "") {  
  30.             var changed = PropertyChanged;  
  31.             if (changed == nullreturn;  
  32.             Invoke(thisnew PropertyChangedEventArgs(propertyName));  
  33.         }  
  34.         public ListViewPageViewModel() {  
  35.             var ordersList = new ObservableCollection < Order > ();  
  36.             ordersList.Add(new Order() {  
  37.                 OrderType = "Completed Orders", TotalCount = "56566"  
  38.             });  
  39.             ordersList.Add(new Order() {  
  40.                 OrderType = "Limit Orders", TotalCount = "878"  
  41.             });  
  42.             ordersList.Add(new Order() {  
  43.                 OrderType = "Market Orders", TotalCount = "39856"  
  44.             });  
  45.             ordersList.Add(new Order() {  
  46.                 OrderType = "Stop Orders", TotalCount = "056708"  
  47.             });  
  48.             ordersList.Add(new Order() {  
  49.                 OrderType = "Imbalance Orders", TotalCount = "64775674"  
  50.             });  
  51.             ordersList.Add(new Order() {  
  52.                 OrderType = "Conditional Orders", TotalCount = "56"  
  53.             });  
  54.             ordersList.Add(new Order() {  
  55.                 OrderType = "Scheduled Orders", TotalCount = "1457575763"  
  56.             });  
  57.             ordersList.Add(new Order() {  
  58.                 OrderType = "Mid-Point Orders", TotalCount = "2443"  
  59.             });  
  60.             ordersList.Add(new Order() {  
  61.                 OrderType = "Odd lot Orders", TotalCount = "65781"  
  62.             });  
  63.             ordersList.Add(new Order() {  
  64.                 OrderType = "Pending Orders", TotalCount = "9896"  
  65.             });  
  66.             OrdersList = ordersList;  
  67.         }  
  68.     }  
  69. }  

Step 2:

In .Net Standard/PCL, create a class name is CustomViewCell which should inherit any ViewCell.

CustomViewCell.cs
  1. using Xamarin.Forms;  
  2. namespace ListViewDemo.CustomControls {  
  3.     public class CustomViewCell: ViewCell {  
  4.         publicstaticreadonly BindableProperty SelectedItemBackgroundColorProperty = BindableProperty.Create("SelectedItemBackgroundColor"typeof(Color), typeof(CustomViewCell), Default);  
  5.         public Color SelectedItemBackgroundColor {  
  6.             get {  
  7.                 return (Color) GetValue(SelectedItemBackgroundColorProperty);  
  8.             }  
  9.             set {  
  10.                 SetValue(SelectedItemBackgroundColorProperty, value);  
  11.             }  
  12.         }  
  13.     }  
  14. }  

Xamarin.Android

In Android project, create a class name as CustomViewCellRenderer and make sure to add renderer registration for our CustomViewCell class above the namespace.

CustomViewCellRenderer.cs

  1. using System.ComponentModel;  
  2. using ListViewDemo.CustomControls;  
  3. using ListViewDemo.Droid.CustomControls;  
  4. using Android.Content;  
  5. using Android.Graphics.Drawables;  
  6. using Android.Views;  
  7. using Xamarin.Forms;  
  8. using Xamarin.Forms.Platform.Android;  
  9. [assembly: ExportRenderer(typeof(CustomViewCell), typeof(CustomViewCellRenderer))]  
  10. namespace ListViewDemo.Droid.CustomControls {  
  11.     public class CustomViewCellRenderer: ViewCellRenderer {  
  12.         private Android.Views.View _cellCore;  
  13.         private Drawable _unselectedBackground;  
  14.         privatebool _selected;  
  15.         protectedoverrideViews.View GetCellCore(Cell item, Views.View convertView, ViewGroup parent, Context context) {  
  16.             _cellCore = base.GetCellCore(item, convertView, parent, context);  
  17.             _selected = false;  
  18.             _unselectedBackground = _cellCore.Background;  
  19.             return _cellCore;  
  20.         }  
  21.         protectedoverridevoid OnCellPropertyChanged(object sender, PropertyChangedEventArgs args) {  
  22.             base.OnCellPropertyChanged(sender, args);  
  23.             if (args.PropertyName == "IsSelected") {  
  24.                 _selected = !_selected;  
  25.                 if (_selected) {  
  26.                     var extendedViewCell = sender as CustomViewCell;  
  27.                     _cellCore.SetBackgroundColor(extendedViewCell.SelectedItemBackgroundColor.ToAndroid());  
  28.                 } else {  
  29.                     _cellCore.SetBackground(_unselectedBackground);  
  30.                 }  
  31.             }  
  32.         }  
  33.     }  
  34. }  
Here OnCellPropertyChanged method instantiates background for ListView selected item.

Xamarin.iOS

In the iOS project, create a class name as CustomViewCellRenderer and make sure to add renderer registration for our RoundedCornerView class above the namespace.

CustomViewCellRenderer.cs

  1. using ListViewDemo.CustomControls;  
  2. using UIKit;  
  3. using Xamarin.Forms;  
  4. using Xamarin.Forms.Platform.iOS;  
  5. using ListViewDemo.iOS.CustomControls;  
  6. [assembly: ExportRenderer(typeof(CustomViewCell), typeof(CustomViewCellRenderer))]  
  7. namespace ListViewDemo.iOS.CustomControls {  
  8.     public class CustomViewCellRenderer: ViewCellRenderer {  
  9.         publicoverride UITableViewCell GetCell(Cell item, UITableViewCell reusableCell, UITableView tv) {  
  10.             var cell = base.GetCell(item, reusableCell, tv);  
  11.             var view = item as CustomViewCell;  
  12.             SelectedBackgroundView = new UIView {  
  13.                 BackgroundColor = view.SelectedItemBackgroundColor.ToUIColor(),  
  14.             };  
  15.             return cell;  
  16.         }  
  17.     }  
  18. }   
Here GetCell override method instantiates background for ListView selected item.

Output:

Please download the source code from here.

How To Change ListView SelectedItem Bg Color In Xamarin.Forms     How To Change ListView SelectedItem Bg Color In Xamarin.Forms