Skip to content

Instantly share code, notes, and snippets.

@dwhathaway
Created April 8, 2015 16:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dwhathaway/1760f47105fab46f7e9d to your computer and use it in GitHub Desktop.
Save dwhathaway/1760f47105fab46f7e9d to your computer and use it in GitHub Desktop.
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