Adding Command to Checkbox in listview xamarin

Viewed 2976

I have a listview in Xamarin forms and I am trying to get a checkbox in each row with a command attached to it.

I have tried some things but nothing worked out yet, because I can't get the binded ID with it.

The things that I have already tried are:

  • Adding a CheckedChanged parameter to the checkbox, I can only get true or false, but not the item this is about.
<CheckBox VerticalOptions="End" x:Name="Checkbox" IsChecked="{Binding IsBought, Mode=TwoWay}" WidthRequest="100" CheckedChanged="Checkbox_CheckedChanged"/>
  • Tried with GestureRecognizers with CommandParameter, this won't even call the function attached to it. I tried this with Tapped and Command, maybe I need to do the command with Binding?
<CheckBox VerticalOptions="End" x:Name="Checkbox" IsChecked="{Binding IsBought, Mode=TwoWay}" WidthRequest="100" CheckedChanged="Checkbox_CheckedChanged">
  <CheckBox.GestureRecognizers>
    <TapGestureRecognizer Command="TapGestureRecognizer_Tapped" CommandParameter="{Binding ArtikelID}"/>
  </CheckBox.GestureRecognizers>
</CheckBox>

I hope you can help me further :) Have a nice day

2 Answers

use the sender's BindingContext

void OnCheckBoxCheckedChanged(object sender, CheckedChangedEventArgs e)
{
    var cb = (CheckBox)sender;
    var item = (MyModel)cb.BindingContext;
    var id = item.ArtikelID;
}

As I understand you have a command property in your ViewModel, and you want to bind every checkBox's command to that command in ViewModel, and pass the item as parameter.

In your case you have to specify the DataContext for that binding, as it is pointing to the item in that list.

Use RelativeSource to solve your problem.

Related