Quantcast
Channel: Xamarin.Forms — Xamarin Community Forums
Viewing all articles
Browse latest Browse all 91519

How to know which item in a ListView is being clicked and then perform an operation on that item?

$
0
0

I have a ViewCell that's bound to a model, which is generated in a ContentPage. In the ContentPage I have something like this:

List<Item> myList = new List<Item>();
ListView myListView = new ListView();

getItems();  // Fills up the list with Items from a database

myListView.HasUnevenRows = true;
myListView.ItemsSource   = myList;
myListView.ItemTemplate  = new DataTemplate(typeof(ItemEntry));  // Is there any way to use a constructor for ItemEntry that has parameters?

eventsListStack.VerticalOptions = LayoutOptions.FillAndExpand;
eventsListStack.Children.Add(myListView);

Content = new StackLayout
{
    Children = 
    {
        eventsListStack,
    }
};

I'd like to setup a clickable event that deletes an Item in the list when the Item (not a button but have the entire Item clickable) is clicked. So I somehow need to have a reference to the specific Item clicked and then remove it from the myList via myList.Remove(Item). I was thinking to have a reference to the ContentPage passed in the constructor of the ItemEntry, and then have this bit of code within ItemEntry:

public ItemEntry(ContentPage ContentPageReference) {  // ViewCell custom constructor
[...]
var itemClick = new TapGestureRecognizer();
itemClick.Tapped += (s, e) => ContentPageReference.OnEventClicked(itemID);
ItemStackLayout.GestureRecognizers.Add(itemClick);
}

So each Item would then send the itemID to the ContentPage's OnEventClicked(string itemID) so that I can delete it there from the list, but unfortunately there doesn't seem to be a way to call the custom constructor with a parameter when binding the DataTemplate. Is there any other way for me to setup a click event and know which Item is being clicked in the list?


Viewing all articles
Browse latest Browse all 91519

Trending Articles