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. public Color SwitchOffColor
  8. {
  9. get { return (Color)GetValue(SwitchOffColorProperty); }
  10. set { SetValue(SwitchOffColorProperty, value); }
  11. }
  12. public static readonly BindableProperty SwitchOnColorProperty =
  13. BindableProperty.Create(nameof(SwitchOnColor),
  14. typeof(Color), typeof(CustomSwitch),
  15. Color.Default);
  16. public Color SwitchOnColor
  17. {
  18. get { return (Color)GetValue(SwitchOnColorProperty); }
  19. set { SetValue(SwitchOnColorProperty, value); }
  20. }
  21. public static readonly BindableProperty SwitchThumbColorProperty =
  22. BindableProperty.Create(nameof(SwitchThumbColor),
  23. typeof(Color), typeof(CustomSwitch),
  24. Color.Default);
  25. public Color SwitchThumbColor
  26. {
  27. get { return (Color)GetValue(SwitchThumbColorProperty); }
  28. set { SetValue(SwitchThumbColorProperty, value); }
  29. }
  30. public static readonly BindableProperty SwitchThumbImageProperty =
  31. BindableProperty.Create(nameof(SwitchThumbImage),
  32. typeof(string),
  33. typeof(CustomSwitch),
  34. string.Empty);
  35. public string SwitchThumbImage
  36. {
  37. get { return (string)GetValue(SwitchThumbImageProperty); }
  38. set { SetValue(SwitchThumbImageProperty, value); }
  39. }
  40. }
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. private void UpdateSwitchThumbImage(CustomSwitch view)
  29. {
  30. if (!string.IsNullOrEmpty(view.SwitchThumbImage))
  31. {
  32. view.SwitchThumbImage = view.SwitchThumbImage.Replace(".jpg", "").Replace(".png", "");
  33. int imgid = (int)typeof(Resource.Drawable).GetField(view.SwitchThumbImage).GetValue(null);
  34. Control.SetThumbResource(Resource.Drawable.icon);
  35. }
  36. else
  37. {
  38. Control.ThumbDrawable.SetColorFilter(view.SwitchThumbColor.ToAndroid(), PorterDuff.Mode.Multiply);
  39. // Control.SetTrackResource(Resource.Drawable.track);
  40. }
  41. }
  42. private void OnCheckedChange(object sender, CompoundButton.CheckedChangeEventArgs e)
  43. {
  44. if (this.Control.Checked)
  45. {
  46. this.Control.TrackDrawable.SetColorFilter(view.SwitchOnColor.ToAndroid(), PorterDuff.Mode.SrcAtop);
  47. }
  48. else
  49. {
  50. this.Control.TrackDrawable.SetColorFilter(view.SwitchOffColor.ToAndroid(), PorterDuff.Mode.SrcAtop);
  51. }
  52. }
  53. protected override void Dispose(bool disposing)
  54. {
  55. this.Control.CheckedChange -= this.OnCheckedChange;
  56. base.Dispose(disposing);
  57. }
  58. }
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")