Mar 18

What is Observable Collection?

An observableCollection represents a dynamic data collection that provides notifications when items get added, removed, or when the whole list is refreshed.  Whenever you modify the collection, the view is notified.

The advantage of ObservableCollection over List is that it implements INotifyCollectionChanged. This interface raises an event whenever the collection is modified by insertion, removal, or replacement. A List does not implement this interface, so anything data bound to it will not be notified when it changes.

Let’s take an example, I have an entity called Person defined below.

[DataContract]public class Person{

[DataMember]

public String FirstName { get; set; }

[DataMember]

public String MiddleName { get; set; }

[DataMember]

public String LastName { get; set; }

[DataMember]

public int Age { get; set; }

[DataMember]

public String Address { get; set; }

}

Now, I need to create an observable collection property which will contain the collection of entity Person.

private ObservableCollection<Person> _personEntityList;public ObservableCollection<Person> PersonEntityList{get

{

if (_personEntityList == null)

_personEntityList = new ObservableCollection<Person>();

return _ personEntityList;

}

set

{

_personEntityList = value;

if (_personEntityList.Count != 0)

{

SelectedPerson = PersonEntityList [0].ToString();

}

 

this.RaisePropertyChanged(() => this. PersonEntityList);

}

 

Adding One CLR property to which value is assigned from above observable collection.

private string _selectedPerson = “No one is selected”;public string SelectedPerson{get

{

return _ selectedPerson;

}

set

{

_ selectedPerson = value;

this.RaisePropertyChanged(() => this. SelectedPerson);

}

}

Whenever any Remove,  Add, Clear() methods are called on this observable collection, the view is notified.

ChartEntityList.Add(PersonData);Here, PersonData is a CLR property of Person type.
private Person _personData = new Person();
public Person PersonData
{
get
{
return _personData ;
}
set
{
_personData = value;
this.RaisePropertyChanged(() => this.PersonData);
}
}

Binding property on UI

<TextBlock Name=”txtSelectedPersonName” Text=”{Binding SelectedPerson, Mode=TwoWay}”
HorizontalAlignment=”Left” FontWeight=”Bold” Margin=”2,0,0,0″ VerticalAlignment=”Center” />

 

Permanent link to this article: http://zappmania.in/2013/03/18/what-is-observable-collection.htm

Leave a Reply

Your email address will not be published.