How to remove an item from a Xamarin Forms ListView?
Here is what you could do :
This be my model class :
public class Item
{
public string ItemName { get; set; }
public string ItemDetails { get; set; }
}
And in my XAML or you can write this in code as well, bind to the Command Parameter
of your Item template :
<Button Text="Delete" CommandParameter="{Binding ItemName}" Clicked="DeleteClicked"></Button>
Full Item Template will be like below :
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<ViewCell.View>
<StackLayout Orientation="Horizontal">
<Label Text="{Binding ItemName}" HorizontalOptions="StartAndExpand" FontSize="30"></Label>
<Button Text="Delete" CommandParameter="{Binding ItemName}" Clicked="DeleteClicked">
</Button>
</StackLayout>
</ViewCell.View>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
And in you code file you can do this :
public void DeleteClicked(object sender, EventArgs e)
{
var item = (Xamarin.Forms.Button)sender;
Item listitem = (from itm in allItems
where itm.ItemName == item.CommandParameter.ToString()
select itm)
.FirstOrDefault<Item>();
allItems.Remove(listitem);
}
IMPORTANT : This would only delete the item from the bound collection. To delete it from the original list you need to use ObservableCollection
Here is the full source code of the explained scenario - Handling Child Control Event in Listview using XAMARIN.FORMS.
Also the Tutorial - How to handle Row selection and delete Button in Row For Custom ListView using Xamarin.Forms explain deletion from a listview
as well.
I've found a similar approach and I want to share it. I filled the list with an ObservableCollection<MyObject>
. Then I filled the CommandParameter with just CommandParameter="{Binding .}"
. So I got the whole Object back. Then you can just cast the CommandParameter
to your Object and remove it from the ObservableCollection<MyObject>
List
XAML:
CommandParameter="{Binding .}"
Filling my List:
savingExpensesCollection = new ObservableCollection<SavingsExpensesEntry> ();
savingExpensesCollection .Add (new SavingsExpensesEntry ("1000 mAh Akku", "Dampfgarten", new DateTime (635808692400000000), 8.95));
savingExpensesCollection .Add (new SavingsExpensesEntry ("Cool-Mint Aroma", "Dampfgarten", new DateTime (635808692400000000), 3.95));
savingExpensesCollection .Add (new SavingsExpensesEntry ("Basis", "Dampfgarten", new DateTime (635808692400000000), 13.65));
savingExpensesList.ItemsSource = savingExpenses;
EventHandler:
void OnDelete(object sender, EventArgs e)
{
var menuItem = ((MenuItem)sender);
SavingsExpensesEntry see ((SavingsExpensesEntry)menuItem.CommandParameter);
savingExpensesCollection .Remove (see);
}
I've using a MenuItem
but it's the same approach with a Button