Home > Net >  Get index of ListView item when RadioButton on one row is clicked in Xamarin Form
Get index of ListView item when RadioButton on one row is clicked in Xamarin Form

Time:01-22

I am implementing 4 RadioButtons in one ListView row and binding them with the model properties. The problem is when the user changes the pre-setted property and the CheckedChanged event fires, how can I get on which row(Index) the user has changed the property?

Here is my Implementation of ListView.

<ListView x:Name ="personlist" ItemsSource="{Binding PersonList}" ItemSelected="personlist_ItemSelected" SelectionMode="Single">
                <ListView.ItemTemplate>
                    <DataTemplate>
                        <ViewCell>
                            <Grid RowDefinitions="*" ColumnDefinitions="3*,*,*,*,*" BackgroundColor="{Binding RowColor}">
                                <Label Text="{Binding Name}" Grid.Row="0" Grid.Column="0" VerticalTextAlignment="Center" FontSize="20" TextColor="Black"/>
                                <RadioButton Value="Travel" IsChecked="{Binding Travel, Mode=TwoWay}" Grid.Row="0" Grid.Column="1" CheckedChanged="RadioButton_CheckedChanged"/>
                                <RadioButton Value="Reading" IsChecked="{Binding Reading, Mode=TwoWay}" Grid.Row="0" Grid.Column="2" CheckedChanged="RadioButton_CheckedChanged"/>
                                <RadioButton Value="Sports" IsChecked="{Binding Sports, Mode=TwoWay}" Grid.Row="0" Grid.Column="3" CheckedChanged="RadioButton_CheckedChanged"/>
                                <RadioButton Value="Dance" IsChecked="{Binding Dance, Mode=TwoWay}" Grid.Row="0" Grid.Column="4" CheckedChanged="RadioButton_CheckedChanged"/>
                            </Grid>
                        </ViewCell>
                    </DataTemplate>
                </ListView.ItemTemplate>
</ListView>

In .xaml.cs

private void RadioButton_CheckedChanged(object sender, CheckedChangedEventArgs e)
{
   // I want to get an index of the list item here.
}

Is there any way to achieve it? this way or other.

Thanks in advance!

CodePudding user response:

use the BindingContext

private void RadioButton_CheckedChanged(object sender, CheckedChangedEventArgs e)
{
   var button = (RadioButton)sender;
   var item = (MyClassName)button.BindingContext;
}

item will be the object that is bound to that row in the ListView

  •  Tags:  
  • Related