Search code examples
xamarinlabelcellcollectionview

Xamarin - Get value from label inside clicked cell of collectionView


I have a collectionView, that is automatically populated via Binding source. In each cell I have a few Labels. When I click on a Label, I'd need to be able to read the value of one of those labels.. (in the sample below it is "PhotographerCode") This is what I have so far, but I cannot figure out how to access the label from the code once the event is fired...

<StackLayout>
        <Button Text="Populate DB" 
                x:Name="populateButton" 
                Clicked="populateButton_Clicked"/>
        <CollectionView ItemsSource="{Binding GalleryList}">
            <CollectionView.ItemsLayout>
                <GridItemsLayout Orientation="Vertical"
                    Span="1" />
            </CollectionView.ItemsLayout>
            <CollectionView.ItemTemplate>
                <DataTemplate>
                    <ViewCell x:Name="Cell"  Tapped="Cell_Tapped">
                    <Grid Padding="10" ColumnSpacing="0" RowSpacing="0">


                        <Label Grid.Row="0" Grid.Column="0" Grid.ColumnSpan="3" Text="{Binding GalleryName}" FontSize="Large" BackgroundColor="LightGray"></Label>
                        <Label Grid.Row="1" Grid.Column="0" Text="Photographer: " FontSize="Small"  BackgroundColor="LightGray"></Label>
                        <Label Grid.Row="1" Grid.Column="1" Grid.ColumnSpan="2" Text="{Binding PhotographerName}" FontSize="Default" BackgroundColor="LightGray"></Label>
                        <Label Grid.Row="2" Grid.Column="0" Text="Code: " FontSize="Small" BackgroundColor="LightGray"></Label>
                        <Label x:Name="PhotographerCode" Grid.Row="2" Grid.Column="1" Text="{Binding PhotographerCode}" FontSize="Small" BackgroundColor="LightGray"></Label>
                        <Label Grid.Row="2" Grid.Column="2" Text="{Binding GalleryCode}" FontSize="Small" BackgroundColor="LightGray"></Label>
                    </Grid>
                    </ViewCell>
                </DataTemplate>
            </CollectionView.ItemTemplate>
        </CollectionView>
    </StackLayout>

and the .cs file:

 private void Cell_Tapped(object sender, EventArgs e)
    {
       ....
    }

Solution

  • CollectionView has built in support for this

    <CollectionView ItemsSource="{Binding GalleryList}" SelectionMode="Single" SelectionChanged="OnCollectionViewSelectionChanged">
    

    then in your event handler

    void OnCollectionViewSelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        var item = (MyModelClass)e.CurrentSelection.FirstOrDefault();
    
        ....
    }
    

    you also do not need to (and should not) use any of the *Cell elements with CollectionView. Those were required for ListView and have been replaced by generic templates with CollectionView