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
- Shared Code
- Xamarin.Android
- 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".
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.
Give the App Name i.e XFSegmentControlDemo.
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.
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
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
Now, Search plugin with Plugin.Segmented name.
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
- <?xml version="1.0" encoding="utf-8"?>
- <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">
- <StackLayout VerticalOptions="FillAndExpand" Padding="30" Spacing="20">
- <Label Text="Segmented Control" FontSize="30" TextColor="White" HorizontalOptions="CenterAndExpand" />
- <control:SegmentedControl x:Name="SegmentedControl" SelectedSegment="{Binding SegmentSelection}" TintColor="White" SelectedTextColor="BlueViolet" DisabledColor="Gray" Margin="8,8,8,8">
- <control:SegmentedControl.Children>
- <control:SegmentedControlOption Text="Item 1" />
- <control:SegmentedControlOption Text="Item 2" />
- <control:SegmentedControlOption Text="Item 3" />
- <control:SegmentedControlOption Text="Item 4" />
- </control:SegmentedControl.Children>
- </control:SegmentedControl>
- <Label Text="{Binding SelectedSegment}" FontSize="40" TextColor="White" HorizontalOptions="CenterAndExpand" VerticalOptions="CenterAndExpand" />
- </StackLayout>
- </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
- using Plugin.Segmented.Control;
- using Plugin.Segmented.Event;
- using Xamarin.Forms;
- using XFSegmentControlDemo.ViewModels;
- namespace XFSegmentControlDemo.Views {
- public partial class HomePage: ContentPage {
- HomePageViewModel _homePageViewModel;
- public HomePage() {
- InitializeComponent();
- _homePageViewModel = new HomePageViewModel();
- BindingContext = _homePageViewModel;
- OnSegmentSelected += (object sender, SegmentSelectEventArgs e) => {
- var selectedSegment = ((SegmentedControl) sender).SelectedSegment;
- _homePageViewModel.SelectedSegment = selectedSegment;
- };
- }
- }
- }
ViewModels
HomePageViewModel.cs
- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Runtime.CompilerServices;
- namespace XFSegmentControlDemo.ViewModels {
- publicclass HomePageViewModel: INotifyPropertyChanged {
- int _selectedSegement;
- public int SelectedSegment {
- get {
- return _selectedSegement;
- }
- set {
- _selectedSegement = value;
- switch (SelectedSegment) {
- case 0:
- break;
- case 1:
- break;
- case 2:
- break;
- case 3:
- break;
- }
- OnPropertyChanged("SelectedSegment");
- }
- }
- protectedbool SetProperty < T > (ref T backingStore, T value,
- [CallerMemberName] string propertyName = "", Action onChanged = null) {
- if (EqualityComparer < T > .Default.Equals(backingStore, value)) returnfalse;
- backingStore = value;
- onChanged ? .Invoke();
- OnPropertyChanged(propertyName);
- returntrue;
- }
-
- publicevent PropertyChangedEventHandler PropertyChanged;
- protectedvoid OnPropertyChanged([CallerMemberName] string propertyName = "") {
- var changed = PropertyChanged;
- if (changed == null) return;
- Invoke(this, new PropertyChangedEventArgs(propertyName));
- }
- }
- }
Here, SelectedSegment property will get the selected segment index.
Step 3
Xamarin.iOS
AppDelegate.cs
In AppDelegate we should initialize segementcontrolrenderer like below.
- using Foundation;
- using Plugin.Segmented.Control.iOS;
- using UIKit;
- namespace XFSegmentControlDemo.iOS {
- [Register("AppDelegate")]
- public partial class AppDelegate: global::Xamarin.Forms.Platform.iOS.FormsApplicationDelegate {
- publicoverridebool FinishedLaunching(UIApplication app, NSDictionary options) {
- global::Xamarin.Forms.Forms.Init();
- SegementedControlRenderer.Initialize();
- LoadApplication(new App());
- return base.FinishedLaunching(app, options);
- }
- }
- }
Output
Please download the source code from here.
.