Introduction
What if an objects list or collection is changed during the application process, how does the control (XAML side) know that changes are happening and then updating tasks are done?
But in this case, we will rectify a little bit the previous question which will be: what if the changes affect an object's collection and not a single object property? In this case, the INotifyPropertyChanged is not sufficient to leverage a complete notification process. Therefore, Silverlight 2 provides us the INotifyCollectionChanged interface. Ok, very well, but always the same question how does one implement that?
The answer is illustrated through this example
Always with our Person object, we try to do the experiment. The object person will be a little bit rectified. The ToString () method will be overridden to give the following class Person feature.
- public class Person {
- public Person() {}
- public Person(string FirstName, string LastName, string PseudoName) {
- this.FirstName = FirstName;
- this.LastName = LastName;
- this.PseudoName = PseudoName;
- }
- public string FirstName {
- get;
- set;
- }
- public string LastName {
- get;
- set;
- }
- public string PseudoName {
- get;
- set;
- }
- public override string ToString() {
- return string.Format("First name: {0}, Last name: {1}, Pseudo name: {2}", FirstName, LastName, PseudoName);
- }
- }
Now, to implement the INotifyCollectionChanged, we have to ways, namely the easy one which makes use of ObservableCollection<T> that already implements the INotifyCollectionChanged, the second way, or let us say the hard one, as a part of which the INotifyCollectionChanged will be implemented by ourselves.
To leverage that let's consider the under XAML implementation
- <UserControl xmlns:data="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data" x:Class="Silverlight.Page"
- xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
- xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
- xmlns:code="clr-namespace:Silverlight"
- Width="600" Height="200">
- <Grid x:Name="LayoutRoot" MouseEnter="LayoutRoot_MouseEnter"
- MouseLeave="LayoutRoot_MouseLeave"
- Background="Azure">
-
- <ListBox FontSize="16"
- x:Name="myItemsControl">
- </ListBox>
- </Grid>
- </UserControl>
The purpose, in this case, is to populate the ListBox myItemsControl then make a test whether this ListBox will be notified or not when updates operations are leveraged at the source level.
The easy scenario
In fact, this is the most adopted way. The ObservableCollection<T> is inherited in this case, the ObservableCollection<T> already implements the INotifyCollectionChanged, and thus, any update operations those affect the collection will be automatically reflected at the XAML side.
First, let's include the namespace System.Collections.ObjectModel and then define a class that inherits the ObservableCollection<Person> as bellow-
- public class AuthorsCollection: ObservableCollection < Person > {
- public AuthorsCollection() {
- Add(new Person {
- FirstName = "Bejaoui",
- LastName = "Bechir",
- PseudoName = "Yougerthen"
- });
- Add(new Person {
- FirstName = "Bejaoui",
- LastName = "Bechir",
- PseudoName = "Yougerthen"
- });
- Add(new Person {
- FirstName = "Bejaoui",
- LastName = "Bechir",
- PseudoName = "Yougerthen"
- });
- Add(new Person {
- FirstName = "Bejaoui",
- LastName = "Bechir",
- PseudoName = "Yougerthen"
- });
- }
- }
Then we define a control instance that targets the XAML UI control and an instance of the above collection, at the other hand, the ListBox ItemsSource property should be set to the newly instantiated data source object as under,
- ItemsControl oControl;
- AuthorsCollection collection;
- public Page() {
- InitializeComponent();
- oControl = LayoutRoot.FindName("myItemsControl") as ListBox;
- collection = new AuthorsCollection();
- oControl.ItemsSource = collection;
- }
Now, let's test whether the updates' operations are reflected in the XAML side or not. For that, we do implement both mouse enter and mouse leave event handlers' stubs in the code behind as follow-
Finally, let's fire up the application and observe now if the mouse enters the grid zone will look like
Figure 1
And if the mouse leaves the grid zone will look like
Figure 2
The hard scenario
In this hard way section, we will implement the INotifyCollectionChanged by ourselves:
First, let's add a reference to System.Collections.Specialized. As the information will be presented in form of a Person list, and then we do create a class that inherits the generic list type of persons and that implements the INotifyCollectionChanged as under:
- public class PersonCollection:List<Person>,INotifyCollectionChanged
- {
-
-
-
-
- #region INotifyCollectionChanged Members
- public event NotifyCollectionChangedEventHandler CollectionChanged
- #endregion
- }
In the beginning, let us add two protected methods within this class, one for adding new members and another one for removing targeted members. We mark them as protected because this class will be inherited later and those couple of methods will be used in the derived class to add and remove persons. The final implementation will be as under-
- public class PersonCollection: List < Person > ,
- INotifyCollectionChanged {
-
-
-
-
-
- protected void Add(Person person) {
- base.Add(person);
- if (CollectionChanged != null) {
- CollectionChanged(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add));
- }
- }
-
-
-
-
-
- protected void Remove(Person person) {
- base.RemoveAt(this.IndexOf(person));
- if (CollectionChanged != null) {
- CollectionChanged(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove));
- }
- }
-
-
-
- #region INotifyCollectionChanged Members
- public event NotifyCollectionChangedEventHandler CollectionChanged;#endregion
-
- }
Then we do create a new class that inherits the above one, it is defined as under:
-
-
-
- public class AuthorsCollection: PersonCollection {
- public AuthorsCollection() {
- Add(new Person {
- FirstName = "Bejaoui",
- LastName = "Bechir",
- PseudoName = "Yougerthen"
- });
- Add(new Person {
- FirstName = "Bejaoui",
- LastName = "Bechir",
- PseudoName = "Yougerthen"
- });
- Add(new Person {
- FirstName = "Bejaoui",
- LastName = "Bechir",
- PseudoName = "Yougerthen"
- });
-
- }
- public List < Person > ToList() {
- return this.ToList < Person > ();
- }
- }
Now, let's move to the XAML editor and add an ItemsControl as follow:
- < UserControl xmlns: data = "clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data"
- x: Class = "Silverlight.Page"
- xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation"
- xmlns: x = "http://schemas.microsoft.com/winfx/2006/xaml"
- Width = "600"
- Height = "200" > <Grid x: Name = "LayoutRoot"
- MouseEnter = "LayoutRoot_MouseEnter"
- MouseLeave = "LayoutRoot_MouseLeave"
- Background = "Azure" >
-
- <ItemsControl FontSize = "16"
- x: Name = "myItemsControl" > </ItemsControl>
-
- </Grid > </UserControl>/
Then we bind our ItemsControl to the data provided by the "collection" object at the C# code behind the side as follow:
- ItemsControl oControl;
- AuthorsCollection collection;
- public Page()
- {
- InitializeComponent();
- oControl = LayoutRoot.FindName("myItemsControl") as ItemsControl;
- collection = new AuthorsCollection();
- oControl.ItemsSource = collection.ToList();
- }
To test the ItemsControl against add and remove actions, we add two mouse events to the grid which plays the container role in this case. If the mouse enter occurs, a new person will be added and the ItemsControl will be notified that a new element is added, and then, if the mouse leaves the grid zone, the targeted person will be removed.
The implementations will be as follow-
- private void LayoutRoot_MouseEnter(object sender, MouseEventArgs e) {
- collection.Add(new Person {
- FirstName = "Bejaoui",
- LastName = "Bechir",
- PseudoName = "Yougethen"
- });
- oItemsControl.ItemsSource = collection.ToList();
- }
- private void LayoutRoot_MouseLeave(object sender, MouseEventArgs e) {
- collection.RemoveAt(collection.Count - 1);
- oItemsControl.ItemsSource = collection.ToList();
- }
Now, if the mouse enters the grid zone the ItemsControl will display
Figure 1
And if the mouse leaves the grid zone the ItemsControl will display
Figure 2
In fact, the INotifyCollectionChanged and the INotifyPropertyChanged are both complementary, I mean one complete the other. The INotifyCollectionChanged CollectionChanged event once is implemented, it notifies the XAML UI, whether an element is added or removed, meanwhile, the INotifyPropertyChanged PropertyChanged event once implemented, it notifies the XAML UI about changes those happen at the properties' levels of a given element within the list.
To combine both implementations let's do some rectifications to the Person class public
- public class Person: INotifyPropertyChanged {
- public Person() {}
- public Person(string FirstName, string LastName, string PseudoName) {
- this.FirstName = FirstName;
- this.LastName = LastName;
- this.PseudoName = PseudoName;
- }
- public string FirstName {
- get;
- set;
- }
- public string LastName {
- get;
- set;
- }
- private string _pseudoName;
- public string PseudoName {
- get {
- return _pseudoName;
- }
- set {
- _pseudoName = value;
- if (PropertyChanged != null) {
- PropertyChanged(this, new PropertyChangedEventArgs("PseudoName"));
- }
- }
- }
- public override string ToString() {
- return string.Format("First name: {0}, Last name: {1}, Pseudo name: {2}", FirstName, LastName, PseudoName);
- }#region INotifyPropertyChanged Members
- public event PropertyChangedEventHandler PropertyChanged;#endregion
- }
The INotifyPropertyChanged is viewed in detail as a part of the previous article series
how does C# code behind interact with a XAML interface within a Silverlight 2 context? -INotifyPropertyChanged implementation-Part IV.
- private void LayoutRoot_MouseEnter(object sender, MouseEventArgs e) {
- collection.Add(new Person {
- FirstName = "Bejaoui",
- LastName = "Bechir",
- PseudoName = "Yougerthen"
- });
- Person person = collection[0];
- person.PseudoName = "Sheshonq";
- oControl.ItemsSource = collection.ToList();
- }
- private void LayoutRoot_MouseLeave(object sender, MouseEventArgs e) {
- Person person = collection[0];
- person.PseudoName = "Yougerthen";
- collection.RemoveAt(collection.Count - 1);
- oControl.ItemsSource = collection.ToList();
- }
When the mouse enters the grid zone, the ItemsControl will display
Figure 3
And then when the mouse leaves the grid zone, the ItemsControl will display
Figure 4
As we remark, changes are affecting the collection by adding a new element, meanwhile, the pseudo name of the first element is changed from Yougerthen to Sheshonq and from Sheshonq to Yougerthen respectively according to the mouse events.
Summary
In this article, we learned about C# and XAML within a Silverlight 2 context - INotifyCollectionChanged implementation: Part V.