Reputation: 487
Using Windows Phone 8
So I've been playing around with ObservableCollection
and Listboxes
and binding them but I've never played around with INotifyPropertyChanged
. I hear that this will make a lot of things easier i.e. automatically detecting if the something in the ObservableCollection
changes.
If its not too much to ask is it possible for someone to provide me with a simple code sample which has these functions:
So basically Just adding the items to the ObservableCollection and a button to delete the selected item from the ObservableCollection and this will update the ObsevableCollection.
It's just that I've never understood how the INotifyPropertyChanged
works. Online samples didn't seem to work for me and all I'm asking is a simple sample of that.
UPDATE
I've managed to add ObservableCollection.
public partial class MainPage : PhoneApplicationPage
{
public AddItems LoadItems = new AddItems();
public MainPage()
{
InitializeComponent();
listBox.DataContext = LoadItems;
}
public class Items
{
public string ItemTitle { get; set; }
public string ItemBody { get; set; }
public string FolderID { get; set; }
}
public class AddItems : ObservableCollection<Items>
{
public AddItems()
{
Add(new Items() { ItemTitle = "Book", ItemBody = "A simple Book.", FolderID = Count.ToString() });
Add(new Items() { ItemTitle = "Paper", ItemBody = "Something to write on.", FolderID = Count.ToString() });
Add(new Items() { ItemTitle = "Pen", ItemBody = "Something you use to write.", FolderID = Count.ToString() });
}
}
private void Delete_Click(object sender, RoutedEventArgs e)
{
}
}
Now if I want to delete items from the listbox how can I do that? I tried:
LoadItems.Remove(listBox.SelectedItem);
But that didn't work. How can I delete a selected item and let the ObservableCollection automatically detect that change and do a refresh so it wont show that deleted item?
Thanks!
Upvotes: 0
Views: 2488
Reputation: 89285
ObservableCollection<T>
already implement INotifyCollectionChanged, which makes it notify UI whenever item added or removed from collection. So, for example, along with data-binding, simply calling ObservableCollection<T>.Add()
function is sufficient to add item to collection as well as notify UI to display newly added item without further effort.
INotifyPropertyChanged is a different thing. It is used to notify UI to update displayed value when value of underlying property has changed.
Upvotes: 4
Reputation: 125620
You don't need INotifyPropertyChanged
to handle Add
/Remove
methods: ObservableCollection<T>
will handle these for you.
You need INotifyPropertyChanged
when you need the screen to update when item which is already in the collection changes, e.g. one of it's properties gets different value.
To make that happen T
has to implement INotifyPropertyChanged
, not the ObservableCollectinon
itself.
Upvotes: 3