Search code examples
c#listviewxamarinxamarin.formsxamarin.android

Xamarin - How do i get data binding string value from an ImageCell in a listview when tapped?


I am still fresh into Xamarin, I am having an issue with figuring out how I will get the Binding value of an image cell.

I have a list view using ImageCell as shown below, iv'e set the itemSelected command to the listview named "selectedBox_Tapped"

    <Grid>
        <ListView x:Name="itemListView" ItemSelected="selectedBox_Tapped">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <ImageCell Text="{Binding Name}"
                        Detail="{Binding Compound}"
                               ImageSource="defaultImage.png">
                    </ImageCell>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
    </Grid>

in the C# code behind, I'm attempting this

    private async void selectedBox_Tapped(object sender, ItemTappedEventArgs args)
    {
        string name = ????

        await Navigation.PushAsync(new DetailsPage(name));
    }

I Would like to be able to get the string value of the {Binding Name} from the ImageCell and then pass it to my DetailsPage as a constructor as shown above.

where String name = ???? I cannot figure out what I need to do to make this work.

Thank you for your help :)


Solution

  • use ItemTappedEventArgs

    private async void selectedBox_Tapped(object sender, ItemTappedEventArgs args)
    {
        // args.Item will be the context of the tapped cell
        // you will need to cast it to the correct class
        var item = (MyClass)args.Item;
    
        // once item is cast, you can just refer to its properties
        await Navigation.PushAsync(new DetailsPage(item.Name));
    }