How to Add Checkmarks to a ListView in Xamarin Forms

iOS Development

How to Add Checkmarks to a ListView in Xamarin…

Recently, I was working on an app with Xamarin where I had a long list of colors that the user can pick from. I created a Simple ListView inside my app to display all of the colors in a table. However, this approach presented some unexpected problems such as:

 

  1.  How do I display a preview of the color next to the text label in my ListView Cell?
  2. How do I keep track of what colors are selected by the user?
  3. How to display a checkbox next to a color once it’s selected?

Lucky for us, The last question is pretty easy to solve once you have a basic understanding of how objects work. I recommend creating a custom object similar to the one listed below.  Make sure you add a boolean property called isChecked. Once that is complete, create a List of your custom object and bind it to your ListView. Once this is complete, add the ItemSelected Event Handler to your ListView. This will create a method in your codebehind that will allow you to take action on something once an item is tapped in the ListView.

 

Before we write any code in your event handler we have to add an image of a checkmark to our project in order for it to display in our UI. If you’re having trouble finding images, I recommend this site. Once you have an image, drag and drop the image file to the resources folder in your iOS and Android solutions in Visual Studio. Once that is done. Add an image to your ListView Cell using either XAML or Code.  Be sure to set the source of your Image to the image that you added to your resources folder. At this point, I recommend testing your image but running your project. If you encountered any errors, please fix them at this time. If a checkmark shows up on every cell, your ready to move on to the next step. But first,  change the isVisible property to false on your image so it’s now hidden by default.

Next, create a DataTrigger on your Image. The DataTrigger is responsible for hiding or showing a checkmark everytime the cell is tapped. Please make sure you bind the trigger to the isChecked property we created earlier.  From there create a Setter in the DataTrigger to change the isVisible property of the image to true when the isChecked property has changed.

 

At this point, write any necessary code to change the value when the cell is tapped. Now you should have the desired functionality. My full source code is listed below.

 

 

Xaml:

 

EventHandler

 

Custom Object

 

 

 

dcadmin

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: