0
votes

Could anyone show me the correct way to remove an item from an ObservableCollection, bound to a ListView, using a MenuItem in Xamarin Forms?

Currently, I have a ListView, called MyList, in XAML, and the ItemsSource is set to MyModelList.

In the code-behind, I have:

private ObservableCollection<MyModel> MyModelList = new ObservableCollection<MyModel>();

I also have a MenuItem, called OnDelete, in XAML, with the CommandParameter set to {Binding .}.

When a ListView item is selected, the OnDelete MenuItem appears, and I would like the selected item to be removed from the ObservableCollection when OnDelete is clicked, but I'm not sure how to code this.

1

1 Answers

3
votes
protected void OnDelete(sender, e) 
{
    var mi = ((MenuItem)sender);
    var item = (MyModel)sender.CommandParameter;
    MyModelList.Remove(item);
};

for this to work you will need to bind the CommandParameter of your Menu, like this

<MenuItem CommandParameter="{Binding .}" Clicked="OnDelete" ... />