How to add a Checkbox in Xamarin.Forms

We are going to show step by step how to create a Checkbox for Xamarin.Forms with a very simple code without the use of Custom Renderers.

This checkbox will work on every platform: Android, iOS, UWP… and the final result will be something like:

Checkbox disabled
Checkbox disabled
Checkbox enabled
Checkbox enabled

There are just two steps you need to do:

  • Add your images
  • Create the Checkbox class

After the two steps, I’m going to show you a small example on how to use this checkbox.

Add the Checkbox images

The first thing to do is to choose two images for the checkbox, one enabled and the other disabled (similat to the ones you can see in the previous images).

Add the images as embedded resources
Add the images as embedded resources

Create an Images folder inside your PCL/.NetStandard project and add the two images in it. Be sure to set the two images as Embedded Resources (as in the previous image).



Add the Checkbox class

Now it’s time to create our checkbox class. Inside your PCL/.NetStandard project create the file Checkbox:

Your are now ready to use the checkbox in your apps and it will work for every platform supported by Xamarin. GREAT!

Now I’ll show you a small example on how to use this checkbox inside your App:



Add the Checkbox to your ContentPage

Inside the our ContentPage we have set the ViewModel and then added the checkbox:

The checkbox has two important properties: Checked and Text.

  • Checked is bound to the IsChecked property of the ViewModel and indicates if the checkbox is checked or not
  • Text is bound to the TextCheckBox property of the ViewModel and is the text that appears next to the CheckBox image

In case you want to execute an action after the status of the checkbox is changed, you can use Command  (bound to the OnCheckedChanged inside the ViewModel) otherwise you can remove it from your XAML.

Create the ViewModel

The ViewModel used in our example is very easy and you can change it as you prefer. For this simple example we have just created a basic ViewModel:

As usual the ViewModel inherits from INotifyPropertyChanged.

We have added two properties IsChecked and TextCheckBox and the Command OnCheckedChanged required only if we want to execute an action after the status of the checkbox is changed.

When the IsChecked value changes, we set the Checkbox text to Is Enabled or Is Disabled according to its value.

Conclusion

In this tutorial we have seen how to create a Checkbox in Xamarin.Forms.

The code is incredibly easy and ready to be used (you can copy and paste the code and it will work).

If you have questions or doubts leave here a comment.

If you need more info about the MVVM pattern in Xamarin you can check the Microsoft documentation here: https://docs.microsoft.com/en-us/xamarin/xamarin-forms/xaml/xaml-basics/data-bindings-to-mvvm

Leave a Reply