xamarincollectionview

Tap an image in a collection view item to get the attributes of that item


Good day, I'm using a collection view to view a user list of addresses in Xamarin Forms and I have an image in the data template for the user to tap on to edit any desired address. See below code. My question, how to get the address details when the user tap the image and display it in another page for editing and saving.

 <CollectionView x:Name="addressCollectionList"
                                    SelectionMode="Single"
                                    SelectionChanged="addressCollectionList_SelectionChanged"
                                    Margin="15">
                        <CollectionView.ItemsLayout>
                            <LinearItemsLayout Orientation="Vertical"/>
                        </CollectionView.ItemsLayout>
                        <CollectionView.ItemTemplate>
                            <DataTemplate>
                                <Grid Padding="5">
                                <Frame BorderColor="#009688" CornerRadius="20">
                                <StackLayout Spacing="10" VerticalOptions="Center" Orientation="Horizontal">
                                <Label Text="{Binding addressName}"/>
                                        <Image Source="ic_edit.png" HorizontalOptions="EndAndExpand">
                                            <Image.GestureRecognizers>
                                                <TapGestureRecognizer x:Name="editAddress" Tapped="editAddress_Tapped"/>
                                               
                                            </Image.GestureRecognizers>
                                        </Image>
                                </StackLayout>
                                </Frame>
                             </Grid>
                            </DataTemplate>
                        </CollectionView.ItemTemplate>
                    </CollectionView>

Solution

  • There are two ways based on if you are using MVVM or not.

    For MVVM

    <TapGestureRecognizer Command="{Binding YourCommand}" CommandParameter={Binding .}/>
    

    And receive it like

    YourCommand= new Command<Type>((selectedItem)=>{
    
    });
    

    For non MVVM:

    <TapGestureRecognizer Tapped="EditAddress_Tapped" CommandParameter={Binding .}/>
    

    And get it like so :

     private void EditAddress_Tapped(object sender, EventArgs e)
        {   
            var tappedEvgs = e as TappedEventArgs;
            var data = tappedEvgs.Parameter;
        }