Segmented Control In Xamarin.Forms

Introduction

In this article, we are going to create a Segmented Control in Xamarin.Forms. Segmented Control is a horizontal bar made up of multiple segments. Each segment works as a discrete button and it can display a title or an image.

 
 
Use of SegmentedControl

Segmented Control is used when you want to show/hide the data based on the selected category in the same view. For example, you want to display different lists in the same ListView based on the segment selected.

Let’s create a simple app in which the color of the view changes based on the selected segment from SegmentedControl.

Requirements

  • This article 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 is tested on the same platforms as well.

Description

The creation of 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 a Xamarin.Forms project in Mac system with Visual Studio.

First, open the Visual Studio for Mac and click on "New Project".
 
Segment Control In Xamarin.Forms 

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

Segment Control In Xamarin.Forms 

Give the App Name i.e XFSegmentControlDemo.

Segment Control 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.

Segment Control In Xamarin.Forms 

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

  • XFSegmentControlDemo - It is for Shared Code
  • XFSegmentControlDemo.Droid - It is for Android.
  • XFSegmentControlDemo.iOS - It is for iOS 

Segment Control In Xamarin.Forms 

We need to follow the below few steps to create segment control

.Net Standard/PCL

Step 1

First, we need to add the Plugin.SegmentedControl.Netstandard plugin on all platforms through nuget.

Right, click on Packages->AddPackages

Segment Control In Xamarin.Forms 

Now, Search plugin with Plugin.Segmented name.

Segment Control In Xamarin.Forms 

Step 2

Create your own Xaml page named HomePage.xaml, and make sure to refer "Plugin.Segmented.Control" class in Xaml by declaring a namespace and using the namespace prefix we can renderer the segment contol. The following code example shows how the Plugin.Segmented.Control plugin renderer class can be consumed by a Xaml page:

HomePage.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:control="clr-namespace:Plugin.Segmented.Control;assembly=Plugin.Segmented" xmlns:iOSForms="clr-namespace:Xamarin.Forms.PlatformConfiguration.iOSSpecific;assembly=Xamarin.Forms.Core" iOSForms:Page.UseSafeArea="true" xmlns:local="clr-namespace:XFSegmentControlDemo" x:Class="XFSegmentControlDemo.Views.HomePage">  
  3.     <StackLayout VerticalOptions="FillAndExpand" Padding="30" Spacing="20">  
  4.         <Label Text="Segmented Control" FontSize="30" TextColor="White" HorizontalOptions="CenterAndExpand" />  
  5.         <control:SegmentedControl x:Name="SegmentedControl" SelectedSegment="{Binding SegmentSelection}" TintColor="White" SelectedTextColor="BlueViolet" DisabledColor="Gray" Margin="8,8,8,8">  
  6.             <control:SegmentedControl.Children>  
  7.                 <control:SegmentedControlOption Text="Item 1" />  
  8.                 <control:SegmentedControlOption Text="Item 2" />  
  9.                 <control:SegmentedControlOption Text="Item 3" />  
  10.                 <control:SegmentedControlOption Text="Item 4" />  
  11.             </control:SegmentedControl.Children>  
  12.         </control:SegmentedControl>  
  13.         <Label Text="{Binding SelectedSegment}" FontSize="40" TextColor="White" HorizontalOptions="CenterAndExpand" VerticalOptions="CenterAndExpand" />  
  14.     </StackLayout>  
  15. </ContentPage>  

Note
The "control" 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 segment control.

Make BindingContext in code behind with HomePageViewModel.

HomePage.xaml.cs

  1. using Plugin.Segmented.Control;  
  2. using Plugin.Segmented.Event;  
  3. using Xamarin.Forms;  
  4. using XFSegmentControlDemo.ViewModels;  
  5. namespace XFSegmentControlDemo.Views {  
  6.     public partial class HomePage: ContentPage {  
  7.         HomePageViewModel _homePageViewModel;  
  8.         public HomePage() {  
  9.             InitializeComponent();  
  10.             _homePageViewModel = new HomePageViewModel();  
  11.             BindingContext = _homePageViewModel;  
  12.             OnSegmentSelected += (object sender, SegmentSelectEventArgs e) => {  
  13.                 var selectedSegment = ((SegmentedControl) sender).SelectedSegment;  
  14.                 _homePageViewModel.SelectedSegment = selectedSegment;  
  15.             };  
  16.         }  
  17.     }  
  18. }  

ViewModels

HomePageViewModel.cs
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.ComponentModel;  
  4. using System.Runtime.CompilerServices;  
  5. namespace XFSegmentControlDemo.ViewModels {  
  6.     publicclass HomePageViewModel: INotifyPropertyChanged {  
  7.         int _selectedSegement;  
  8.         public int SelectedSegment {  
  9.             get {  
  10.                 return _selectedSegement;  
  11.             }  
  12.             set {  
  13.                 _selectedSegement = value;  
  14.                 switch (SelectedSegment) {  
  15.                     case 0:  
  16.                         break;  
  17.                     case 1:  
  18.                         break;  
  19.                     case 2:  
  20.                         break;  
  21.                     case 3:  
  22.                         break;  
  23.                 }  
  24.                 OnPropertyChanged("SelectedSegment");  
  25.             }  
  26.         }  
  27.         protectedbool SetProperty < T > (ref T backingStore, T value,  
  28.             [CallerMemberName] string propertyName = "", Action onChanged = null) {  
  29.             if (EqualityComparer < T > .Default.Equals(backingStore, value)) returnfalse;  
  30.             backingStore = value;  
  31.             onChanged ? .Invoke();  
  32.             OnPropertyChanged(propertyName);  
  33.             returntrue;  
  34.         }  
  35.         //INotifyPropertyChanged implementation method   
  36.         publicevent PropertyChangedEventHandler PropertyChanged;  
  37.         protectedvoid OnPropertyChanged([CallerMemberName] string propertyName = "") {  
  38.             var changed = PropertyChanged;  
  39.             if (changed == nullreturn;  
  40.             Invoke(thisnew PropertyChangedEventArgs(propertyName));  
  41.         }  
  42.     }  
  43. }  

Here, SelectedSegment property will get the selected segment index.

Step 3
 
Xamarin.iOS
 
AppDelegate.cs

In AppDelegate we should initialize segementcontrolrenderer like below.
  1. using Foundation;  
  2. using Plugin.Segmented.Control.iOS;  
  3. using UIKit;  
  4. namespace XFSegmentControlDemo.iOS {  
  5.     [Register("AppDelegate")]  
  6.     public partial class AppDelegate: global::Xamarin.Forms.Platform.iOS.FormsApplicationDelegate {  
  7.         publicoverridebool FinishedLaunching(UIApplication app, NSDictionary options) {  
  8.             global::Xamarin.Forms.Forms.Init();  
  9.             SegementedControlRenderer.Initialize();  
  10.             LoadApplication(new App());  
  11.             return base.FinishedLaunching(app, options);  
  12.         }  
  13.     }  
  14. }  

Output

Please download the source code from here.

 .