Simple Use of Observable Collection in Windows Phone

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 .

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", });
}
}

 

Simple Use of Observable Collection in Windows Phone

2 Comments

  1. hhhhha June 4, 2014 Reply
  2. santosh March 22, 2016 Reply

Leave a Reply