Checkbox in Xamarin Forms

Xamarin Forms has many default UI components that can be used by developers. Unfortunately, one of most common components, checkbox is not one of them. So, in this post, I want to discuss about a workaround method that I used to create checkbox in Xamarin Forms. I’ve created a simple To-Do list form to show you how it works, but you will need two images, checked and unchecked box.

Creating Entity Class

First, we have to create an entity class to represent the to-do items. The following code shows you the example of simple entity class. I have one property called IsDone which will determine the status of the item on the list. I also have another property called ImageCheckBox, that I purposely put in different partial class just for tidiness sake, that will determine the image that will be shown base on the item status.


public partial class TodoItem
{
    public string Id { get; set; }
    public string ItemDescription { get; set; }
    public bool IsDone { get; set; }
}

public partial class TodoItem
{
    public string ImageCheckBox
    {
        get
        {
            if (IsDone)
                return "Checked.png";
            else
                return "Unchecked.png";
        }
    }
}

Custom Observable Collection

The next thing we need is a custom class of Observable Collection. Why we need this? Because we gonna put the checkbox in every item on list. It means we need to notify the UI if there’s a change in a single item of the list. But, it’s not how the traditional Observable Collection works. It will only notify the UI if there’s change to list, not to the item on list. If new item’s added to list or removed, to UI will be notified but if the change happen to the list item, in this case we want to change the image of the check box, the UI won’t be notified. So, this is the Custom Observable looks like.


public class CustomObservableCollection : ObservableCollection
{
    public CustomObservableCollection() { }
    public CustomObservableCollection(IEnumerable items) : this()
    {
        foreach (var item in items)
            this.Add(item);
    }
public void ReportItemChange(T item)
    {
        NotifyCollectionChangedEventArgs args =
            new NotifyCollectionChangedEventArgs(
                NotifyCollectionChangedAction.Replace,
                item,
                item,
                IndexOf(item));
        OnCollectionChanged(args);
    }
}

View Model Implementation

Next, we move on to the view model. The one thing that need to be noticed in this view model is the UpdateCheckBox method, which is called from UpdateCheckBoxCommand command, which will be bind to XAML file. That method contains mechanism to notify the list that one certain item is changed.


public class ToDoViewModel : INotifyPropertyChanged
{
    private CustomObservableCollection todoList;
    public CustomObservableCollection ToDoList
    {
        get => todoList;
        set => SetObservableProperty(ref todoList, value);
    }

    public ICommand UpdateCheckBoxCommand { get; set; }

    public ToDoViewModel()
    {
        ToDoList = new CustomObservableCollection()
        {
            new TodoItem(){ Id = "1", ItemDescription = "Task 1", IsDone = false},
            new TodoItem(){ Id = "2", ItemDescription = "Task 2", IsDone = false},
            new TodoItem(){ Id = "3", ItemDescription = "Task 3", IsDone = false},
            new TodoItem(){ Id = "4", ItemDescription = "Task 4", IsDone = false},
                new TodoItem(){ Id = "5", ItemDescription = "Task 5", IsDone = false},
        };

        UpdateCheckBoxCommand = new Command((Id) => UpdateCheckBox(Id));
    }

    private void UpdateCheckBox(string id)
    {
        TodoItem item = ToDoList.FirstOrDefault(x => x.Id == id);
        if (item.IsDone) item.IsDone = false;
        else item.IsDone = true;

        ToDoList.ReportItemChange(item);
    }

    public event PropertyChangedEventHandler PropertyChanged;

    protected void SetObservableProperty(ref T field,T value,
        [CallerMemberName] string propertyName = "")
    {
        if (EqualityComparer.Default.Equals(field, value)) return;
        field = value;
        OnPropertyChanged(propertyName);
    }

    protected virtual void OnPropertyChanged(string propertyName)
        => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}

Command Parameter

And then, we’re going to the XAML file, where we bind the data and the command. One this to notice in this file, we gonna passing a parameter to the command. The parameter is the Id of the item that we want to mark as done or undone. To pass the parameter to a command, first we need to give name to content page page. The name of the content name will be referenced by the command. Notice that I put same name in the x:Name property of Content Page and x:Reference of the Command. The path of the command is method name in view model, and command parameter is the method’s parameter.

checkbox

Final Touch

And now all has been set up, lastly we just need to bind the view model as the binding context to XAML.


[XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class TodoPage : ContentPage
    {
        public TodoPage()
        {
            InitializeComponent();
            BindingContext = new ToDoViewModel();
        }
    }

Now if you run the project, you will find a list consisting of 5 task items with blank check box in the right side. If you want to mark one the them as done task, you can just press the check box and it will trigger the list to change the image and give you sense of using real check box.

UPDATE : Bindable Check Box and Radio Button

4 thoughts on “Checkbox in Xamarin Forms

  1. where is the xaml page you did not provide proper example.please put the xaml page in this blog.i am not able ti implement it.thanks

    Like

    1. Hei Ashish,
      Sorry for late reposnse, I got my hand full during this weekend. I don’t why but recently I can display xaml code anymore on WordPress, so it causes my old post seems incomplete. I already put the screenshot of the xaml code, I hope this will help. Thank you, and sorry for the inconvenience.

      Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s