Xamarin.Forms Custom Switch Control

Introduction

This article demonstrates how to create and use a custom switch control in Xamarin.Forms using XAML and C#. This article starts with the introduction of the CustomSwitch tag in XAML. After that, it demonstrates how to set BorderColor, ThumbColor, and ThumbImage of a Custom Switch.

Xamarin

Implementation

Open Visual Studio and create a "New Project".

Xamarin

Another way to create a project is to go to File >> New>>Project or press ctrl+Shft+N.

Xamarin

Now, select Cross-Platform App, give the project a name, and set the project path. Then, click OK.

Xamarin

Select the template as "Blank App" and code sharing as "PCL".

Xamarin

Right-click on PCL Project and select Add >> New Item or Add >> Class.

Xamarin

Now, we give the class a name as "CustomSwich.cs".

Xamarin

Now, generate the custom properties...

Xamarin

CustomSwitch.cs

  1. public class CustomSwitch : Switch  
  2.    {  
  3.        public static readonly BindableProperty SwitchOffColorProperty =  
  4.          BindableProperty.Create(nameof(SwitchOffColor),  
  5.              typeof(Color), typeof(CustomSwitch),  
  6.              Color.Default);  
  7.   
  8.        public Color SwitchOffColor  
  9.        {  
  10.            get { return (Color)GetValue(SwitchOffColorProperty); }  
  11.            set { SetValue(SwitchOffColorProperty, value); }  
  12.        }  
  13.   
  14.        public static readonly BindableProperty SwitchOnColorProperty =  
  15.          BindableProperty.Create(nameof(SwitchOnColor),  
  16.              typeof(Color), typeof(CustomSwitch),  
  17.              Color.Default);  
  18.   
  19.        public Color SwitchOnColor  
  20.        {  
  21.            get { return (Color)GetValue(SwitchOnColorProperty); }  
  22.            set { SetValue(SwitchOnColorProperty, value); }  
  23.        }  
  24.   
  25.        public static readonly BindableProperty SwitchThumbColorProperty =  
  26.          BindableProperty.Create(nameof(SwitchThumbColor),  
  27.              typeof(Color), typeof(CustomSwitch),  
  28.              Color.Default);  
  29.   
  30.        public Color SwitchThumbColor  
  31.        {  
  32.            get { return (Color)GetValue(SwitchThumbColorProperty); }  
  33.            set { SetValue(SwitchThumbColorProperty, value); }  
  34.        }  
  35.   
  36.        public static readonly BindableProperty SwitchThumbImageProperty =  
  37.          BindableProperty.Create(nameof(SwitchThumbImage),  
  38.              typeof(string),  
  39.              typeof(CustomSwitch),  
  40.              string.Empty);  
  41.   
  42.        public string SwitchThumbImage  
  43.        {  
  44.            get { return (string)GetValue(SwitchThumbImageProperty); }  
  45.            set { SetValue(SwitchThumbImageProperty, value); }  
  46.        }  
  47.    }  
This property is set in the Android project as well as in iOS project.

Let us start with Android. We are creating a Class in Android Project and rendering the Switch. Then, we set all the properties when we generate it in PCL Project.

Xamarin

Please make sure of the dependency [assembly: ExportRenderer(typeof(CustomSwitch), typeof(MySwitchRenderer))] of Android (MySwitchRndered) and PCL (CustomSwitch).

Xamarin

MySwitchRenderer.cs

  1. public class MySwitchRendererd : SwitchRenderer  
  2.     {  
  3.         private CustomSwitch view;  
  4.         protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.Switch> e)  
  5.         {  
  6.             base.OnElementChanged(e);  
  7.             if (e.OldElement != null || e.NewElement == null)  
  8.                 return;  
  9.             view = (CustomSwitch)Element;  
  10.             if (Android.OS.Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.JellyBean)  
  11.             {  
  12.                 if (this.Control != null)  
  13.                 {  
  14.                     if (this.Control.Checked)  
  15.                     {  
  16.                         this.Control.TrackDrawable.SetColorFilter(view.SwitchOnColor.ToAndroid(), PorterDuff.Mode.SrcAtop);  
  17.                     }  
  18.                     else  
  19.                     {  
  20.                         this.Control.TrackDrawable.SetColorFilter(view.SwitchOffColor.ToAndroid(), PorterDuff.Mode.SrcAtop);  
  21.                     }  
  22.                    this.Control.CheckedChange += this.OnCheckedChange;  
  23.                     UpdateSwitchThumbImage(view);  
  24.                 }  
  25.                 //Control.TrackDrawable.SetColorFilter(view.SwitchBGColor.ToAndroid(), PorterDuff.Mode.Multiply);  
  26.             }  
  27.         }  
  28.           
  29.         private void UpdateSwitchThumbImage(CustomSwitch view)  
  30.         {  
  31.             if (!string.IsNullOrEmpty(view.SwitchThumbImage))  
  32.             {  
  33.                 view.SwitchThumbImage = view.SwitchThumbImage.Replace(".jpg""").Replace(".png""");  
  34.                 int imgid = (int)typeof(Resource.Drawable).GetField(view.SwitchThumbImage).GetValue(null);  
  35.                 Control.SetThumbResource(Resource.Drawable.icon);  
  36.             }  
  37.             else  
  38.             {  
  39.                 Control.ThumbDrawable.SetColorFilter(view.SwitchThumbColor.ToAndroid(), PorterDuff.Mode.Multiply);  
  40.                 // Control.SetTrackResource(Resource.Drawable.track);  
  41.             }  
  42.         }  
  43.   
  44.       private void OnCheckedChange(object sender, CompoundButton.CheckedChangeEventArgs e)  
  45.         {  
  46.             if (this.Control.Checked)  
  47.             {  
  48.                 this.Control.TrackDrawable.SetColorFilter(view.SwitchOnColor.ToAndroid(), PorterDuff.Mode.SrcAtop);  
  49.             }  
  50.             else  
  51.             {  
  52.                 this.Control.TrackDrawable.SetColorFilter(view.SwitchOffColor.ToAndroid(), PorterDuff.Mode.SrcAtop);  
  53.             }  
  54.         }  
  55.         protected override void Dispose(bool disposing)  
  56.         {  
  57.             this.Control.CheckedChange -= this.OnCheckedChange;  
  58.             base.Dispose(disposing);  
  59.         }  
  60.     }  
Now, it's time to go to the iOS project and set the PCL (CustomSwitch) properties in iOS Project….

We are creating a Class, so right click on iOS project and select Apple. Then, select "Class" and give this class a name as MySliderRendered.cs.

Xamarin

Now, let us write some code for Switch and Set Properties.

Xamarin

MySwitchRenderer.cs

  1. public class MySwitchRendererd : SwitchRenderer  
  2.     {  
  3.         Version version = new Version(ObjCRuntime.Constants.Version);  
  4.         protected override void OnElementChanged(ElementChangedEventArgs<Switch> e)  
  5.         {  
  6.             base.OnElementChanged(e);  
  7.             if (e.OldElement != null || e.NewElement == null)  
  8.                 return;  
  9.             var view = (CustomSwitch)Element;  
  10.             if (!string.IsNullOrEmpty(view.SwitchThumbImage))  
  11.             {  
  12.                 if (version > new Version(6, 0))  
  13.                 {   //n iOS 6 and earlier, the image displayed when the switch is in the on position.  
  14.                     Control.OnImage = UIImage.FromFile(view.SwitchThumbImage.ToString());  
  15.                     //n iOS 6 and earlier, the image displayed when the switch is in the off position.  
  16.                     Control.OffImage = UIImage.FromFile(view.SwitchThumbImage.ToString());  
  17.                 }  
  18.                 else  
  19.                 {  
  20.                     Control.ThumbTintColor = view.SwitchThumbColor.ToUIColor();  
  21.                 }  
  22.             }  
  23.             //The color used to tint the appearance of the thumb.  
  24.             Control.ThumbTintColor = view.SwitchThumbColor.ToUIColor();  
  25.             //Control.BackgroundColor = view.SwitchBGColor.ToUIColor();  
  26.             //The color used to tint the appearance of the switch when it is turned on.  
  27.             Control.OnTintColor = view.SwitchOnColor.ToUIColor();  
  28.             //The color used to tint the outline of the switch when it is turned off.  
  29.             Control.TintColor = view.SwitchOffColor.ToUIColor();  
  30.         }  
  31.     }  
Now, go to the PCL project and use in the MainPage.xaml.
 

Xamarin

As you can see in the above code, we have to set the view reference in xmlns:custom="clr-namespace:XamarinControlApp.CustomControls" MainPage.xaml.

Write the following code for CustomSwitch.

MainPage.xaml

  1. <ContentPage.Content>  
  2.         <StackLayout Padding="20" BackgroundColor="Gray" >  
  3.             <Label Text="Custom Switch" FontSize="Large"/>  
  4.            <cs:CustomSwitch x:Name="customSwitch"  
  5.                                 SwitchOffColor="Yellow"  
  6.                                  SwitchOnColor="Black"  
  7.                                  SwitchThumbImage="icon"  
  8.                                  HorizontalOptions="CenterAndExpand"  
  9.                                  VerticalOptions="CenterAndExpand"/>  
  10.                 <cs:CustomSwitch SwitchOffColor="Navy"  
  11.                                  SwitchOnColor="Green"  
  12.                                  SwitchThumbColor="Violet"  
  13.                                  HorizontalOptions="CenterAndExpand"  
  14.                                  VerticalOptions="CenterAndExpand"/>  
  15.         </StackLayout>  
  16.     </ContentPage.Content>  

 

Xamarin

Now, you will have your CustomSwitch working!!

NOTE

Not tested on iOS.

Features of CustomSwitch Controls

  1. Custom Switch On Color Property=(SwitchOnColor="Red")
  2. Custom Switch Off Color Property=(SwitchOffColor="Yellow")
  3. Custom Switch Thumb Color Property=(SwitchThumbColor="Yellow")
  4. Custom Thumb Image Property=(SwitchThumbImage="Black")

Up Next
    Ebook Download
    View all
    Learn
    View all