In our previous example we discussed about the simple examples of INotifyPropertyChanged, ICommand which are used in MVVM layout. Today let us discuss about Observable collection.
Observable Collection is nothing but it represents a dynamic data collection that provides notifications when items get added, removed, or when the whole list will be refreshed. Follow this link to refer the description about Observable collection in MSDN.
There are two sentences we should consider here, “dynamic data collection”, and “provides notifications when items get added…”.
- Dynamic data is nothing but a list. A collection of generic type <T> objects, i.e it can keep a collection of any objects.
- It provides notifications when items get added. This definition looks similar to INotifyPropertyChanged. It also notifies when the change is updated. ObservableCollection class is a built in implementation of a data collection that implements INotifyPropertyChanged.
If we use a list we should simply push notifications manually. Mainly ObservableCollection itself only notifies for changes to the collection,. It is not for property changes of the individual objects in the collection.
Let us illustrate an example for Observable collection. In the previous example of INotifyPropertyChanged we created a Notify class and implemented interface. We gonna use the same class to extend our application to use Observable collection. Refer this link for the INotify class and add the below code
class Observ : ObservableCollection<Notify>{this.Add(new Notify { Title = "Myname", Desc = "fine", Year = 2014 });this.Add(new Notify { Title = "Yourname", Desc = "good", Year = 2014 });this.Add(new Notify { Title = "Yourday", Desc = "bad", Year = 2014 });}
We should update our UI to display these items in the list view. So drag and drop the list view control. Add a data template to the listview to bind the text to the text blocks. Add the following code to list view control.
<DataTemplate x:Key="MyDataTemp">
<StackPanel><TextBlock Text="{Binding Title}"/><TextBlock Text="{Binding Desc}"/><TextBlock Text="{Binding Year}"/></StackPanel></DataTemplate>
And just refer the key to the data template with the control name. It looks like
<ListView ItemTemplate="{StaticResource ListViewDataTemplate}" x:Name="lv1"/>
And the final step is done in code behind file. We should add the item source of the listview to the class..
Observ ob = new Observ();lv1.ItemsSource = ob;
So in this way we can add the static data to the observable collections. It is the simplest way. We can also add the dynamic data using some api's where the data will be from requested url.
No comments:
Post a Comment