A newbie would definitely wonder what is Observable Collection in Windows Phone 7 .
Here’s a simple scenario which demonstrates one of the advantages of the Observable Collection .
Simple Use of Observable Collection in Windows Phone
The ObservableCollection notifies the UI when you add the items to your collection to which the ListBox will get Updated .
public partial class MainPage : PhoneApplicationPage { // Constructor public MainPage() { InitializeComponent(); FillListBox(); } MovieList Mov = new MovieList(); private void FillListBox() { listBox1.ItemsSource = Mov; listBox1.DisplayMemberPath = "Name"; listBox1.SelectionChanged += new SelectionChangedEventHandler(listBox1_SelectionChanged); } void listBox1_SelectionChanged(object sender, SelectionChangedEventArgs e) { Mov.Add(new Movie { Name = "Ghillli", Actor = "Vijay" }); } } public class Movie { public string Actor { get; set; } public string Name { get; set; } } public class MovieList : List { public MovieList() { Add(new Movie { Name = "Kaavalan", Actor = "Vijay", }); Add(new Movie { Name = "Velayutham", Actor = "Vijay", }); Add(new Movie { Name = "7th Sense", Actor = "Surya", }); Add(new Movie { Name = "Billa 2", Actor = "Ajith Kumar", }); Add(new Movie { Name = "Nanban", Actor = "Vijay", }); } }
In the above example , we use the the List<Movie> bound to the ItemSource of the Listbox and on the ListBox’s selectionChanged Event , we add another item to the same List .
Try the same thing by making the MovieList as ObservableCollection<Movie> and select the items on the ListBox , You will see that a new item will be added to the Listbox …
public class MovieList : ObservableCollection { public MovieList() { Add(new Movie { Name = "Kaavalan", Actor = "Vijay", }); Add(new Movie { Name = "Velayutham", Actor = "Vijay", }); Add(new Movie { Name = "7th Sense", Actor = "Surya", }); Add(new Movie { Name = "Billa 2", Actor = "Ajith Kumar", }); Add(new Movie { Name = "Nanban", Actor = "Vijay", }); } }
2 Comments
The ObservableCollection notifies the UI when you add the items to your collection to which the ListBox will get Updated ?
How to delete an item from the Observable collection.
private void DeleteFile(object sender, EventArgs e)
{
//SavedData item = ParkListBox.SelectedItem as SavedData;
SavedData item = parkinglistobj.Select(i => i.ID == index) as SavedData;
//ParkListBox.Items.RemoveAt(0);
parkinglistobj.Remove(item);
using (IsolatedStorageFileStream fileStream = Settings.OpenFile(“CardItemList”, FileMode.Open,FileAccess.ReadWrite))
{
DataContractSerializer serializer = new DataContractSerializer(typeof(SavedDataList));
parkinglistobj = (SavedDataList)serializer.ReadObject(fileStream);
}
MessageBox.Show(“Deleted Successfully”);
NavigationService.Navigate(new Uri(“/FilesPage.xaml”, UriKind.RelativeOrAbsolute));
}
I tried in many ways but it was not deleting.