简体   繁体   中英

How to get ObservableCollection item by ListView ContextAction?

I need to delete an item from my ObservableCollection<ViewModels.ZoneViewModel> by using contextactions. I'm trying to do this but I end up deleting nothing as the object I'm trying to delete is just taken from the listview, instead of the observablecollection.

public async void OnDelete(object sender, EventArgs e) {
  var menuItem = ((MenuItem) sender);

  if (menuItem != null) {
    var selectedZone = (ViewModels.ZoneViewModel) menuItem.CommandParameter;

    var deleteAction = await DisplayActionSheet("Delete " + selectedZone.Name + "?", "Cancel", "Delete");

    switch (deleteAction) {
      case "Delete":

        await DisplayAlert("delete Context Action clicked: ", menuItem.CommandParameter + "Name= " + selectedZone.Name + " Address=" + selectedZone.Address + " Image=" + selectedZone.Image, "OK");
        Zones = await BlobCache.UserAccount.GetObject < ObservableCollection < ViewModels.ZoneViewModel >> ("zones");
        Zones.Remove(selectedZone);
        await BlobCache.UserAccount.InsertObject < ObservableCollection < ViewModels.ZoneViewModel >> ("zones", Zones);
        zonesList.ItemsSource = Zones;

        break;
    }

  }

}

So how do I get the right item to delete from my observablecollection, the one that I selected via contextaction?

On this line

Zones = await BlobCache.UserAccount.GetObject < ObservableCollection < ViewModels.ZoneViewModel >> ("zones");

You replace the whole Zones object with a fresh ObservableCollection , causing the object that you want to remove, not being in it anymore. Although you will probably think it is still in there because the properties might be the same, it is a different object.

You can fix it by either not getting a new version of Zones . Or edit the remove more like this:

Zones.Remove(Zones.Single(z => z.Id == selectedZone.Id));

Assuming that the ZoneViewModel object has a property Id which is unique. You would also need to import the Linq using.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM