Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Xamarin.Forms - Delete from ObservableCollection<T>
using System;
using Xamarin.Forms;
using System.Collections.ObjectModel;
namespace SampleDeleteItem
{
public class Item
{
public string Name { get; set; }
public string Email { get; set; }
}
public class App : Application
{
ObservableCollection<Item> Items = new ObservableCollection<Item> ();
Random r = new Random();
public App ()
{
ListView lv = new ListView ();
lv.ItemsSource = Items;
DataTemplate dataTemplate = new DataTemplate (typeof(TextCell));
dataTemplate.SetBinding (TextCell.TextProperty, "Name");
dataTemplate.SetBinding (TextCell.DetailProperty, "Email");
Button addItem = new Button () { Text = "Add Item" };
Button removeItem = new Button () { Text = "Remove Item" };
lv.ItemTemplate = dataTemplate;
addItem.Clicked += (object sender, EventArgs e) => {
Items.Add(new Item() { Name = "David", Email = "dave@xamarin.com" });
};
removeItem.Clicked += (object sender, EventArgs e) => {
if(Items.Count > 0) {
Items.RemoveAt(r.Next(0, Items.Count - 1));
}
};
// The root page of your application
MainPage = new ContentPage {
Content = new StackLayout {
VerticalOptions = LayoutOptions.Center,
Children = {
addItem,
removeItem,
lv
}
}
};
}
protected override void OnStart ()
{
// Handle when your app starts
}
protected override void OnSleep ()
{
// Handle when your app sleeps
}
protected override void OnResume ()
{
// Handle when your app resumes
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment