C# and XAML within a Silverlight 2 context - INotifyCollectionChanged implementation: Part V

Introduction

 
In the previous article, how does C# code behind interact with a XAML interface within a Silverlight 2 context? - INotifyPropertyChanged implementation: Part IV, I gave an example of how to use C# code to implement a notification mechanism so that if property within a given C# source object is changed, updates will automatically propagate and change the targeted dependency property of the XAML UI.  
 
In this article, I will continue the response of the question posed in the article how does a XAML interface interact with C# code behind within a Silverlight 2 context?
 

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.
  1. public class Person {  
  2.   public Person() {}  
  3.   public Person(string FirstName, string LastName, string PseudoName) {  
  4.     this.FirstName = FirstName;  
  5.     this.LastName = LastName;  
  6.     this.PseudoName = PseudoName;  
  7.   }  
  8.   public string FirstName {  
  9.     get;  
  10.     set;  
  11.   }  
  12.   public string LastName {  
  13.     get;  
  14.     set;  
  15.   }  
  16.   public string PseudoName {  
  17.     get;  
  18.     set;  
  19.   }  
  20.   public override string ToString() {  
  21.     return string.Format("First name: {0}, Last name: {1}, Pseudo name: {2}", FirstName, LastName, PseudoName);  
  22.   }  
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
  1. <UserControl xmlns:data="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data"  x:Class="Silverlight.Page"    
  2.     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"    
  3.     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"    
  4.     xmlns:code="clr-namespace:Silverlight"    
  5.     Width="600" Height="200">    
  6.     <Grid x:Name="LayoutRoot"  MouseEnter="LayoutRoot_MouseEnter"    
  7.                                MouseLeave="LayoutRoot_MouseLeave"    
  8.           Background="Azure">    
  9.            
  10.         <ListBox FontSize="16"    
  11.                       x:Name="myItemsControl">    
  12.         </ListBox>    
  13.       </Grid>    
  14. </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-
  1. public class AuthorsCollection: ObservableCollection < Person > {  
  2.   public AuthorsCollection() {  
  3.     Add(new Person {  
  4.       FirstName = "Bejaoui",  
  5.       LastName = "Bechir",  
  6.       PseudoName = "Yougerthen"  
  7.     });  
  8.     Add(new Person {  
  9.       FirstName = "Bejaoui",  
  10.       LastName = "Bechir",  
  11.       PseudoName = "Yougerthen"  
  12.     });  
  13.     Add(new Person {  
  14.       FirstName = "Bejaoui",  
  15.       LastName = "Bechir",  
  16.       PseudoName = "Yougerthen"  
  17.     });  
  18.     Add(new Person {  
  19.       FirstName = "Bejaoui",  
  20.       LastName = "Bechir",  
  21.       PseudoName = "Yougerthen"  
  22.     });  
  23.   }  
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,
  1. ItemsControl oControl;  
  2. AuthorsCollection collection;  
  3. public Page() {  
  4.   InitializeComponent();  
  5.   oControl = LayoutRoot.FindName("myItemsControl"as ListBox;  
  6.   collection = new AuthorsCollection();  
  7.   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:
  1. public class PersonCollection:List<Person>,INotifyCollectionChanged  
  2.     {  
  3.          /* TODO: we implement the code that adds and removes data 
  4.          * without forgetting to notify the target XAML object so that 
  5.          * data display will be changed if any changes happen  
  6.          */  
  7.         #region INotifyCollectionChanged Members  
  8.         public event NotifyCollectionChangedEventHandler CollectionChanged  
  9.         #endregion  
  10.     } 
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-
  1. public class PersonCollection: List < Person > ,  
  2. INotifyCollectionChanged {  
  3.   /// <summary>  
  4.   /// void: Method that enables add a person to  
  5.   /// the list  
  6.   /// </summary>  
  7.   /// <param name="person">Person: Person going to be added</param>  
  8.   protected void Add(Person person) {  
  9.     base.Add(person);  
  10.     if (CollectionChanged != null) {  
  11.       CollectionChanged(thisnew NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add));  
  12.     }  
  13.   }  
  14.   /// <summary>  
  15.   /// void: Method that enables remove a person from  
  16.   /// the list  
  17.   /// </summary>  
  18.   /// <param name="person">Person: Person going to be removed</param>  
  19.   protected void Remove(Person person) {  
  20.     base.RemoveAt(this.IndexOf(person));  
  21.     if (CollectionChanged != null) {  
  22.       CollectionChanged(thisnew NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove));  
  23.     }  
  24.   }  
  25.   /// <summary>  
  26.   /// event: The INotifyCollectionChanged member  
  27.   /// </summary>  
  28.   #region INotifyCollectionChanged Members  
  29.   public event NotifyCollectionChangedEventHandler CollectionChanged;#endregion  
  30.   
Then we do create a new class that inherits the above one, it is defined as under:
  1. /// <summary>  
  2. /// This class inherits the PersonCollection  
  3. /// </summary>  
  4. public class AuthorsCollection: PersonCollection {  
  5.   public AuthorsCollection() {  
  6.     Add(new Person {  
  7.       FirstName = "Bejaoui",  
  8.       LastName = "Bechir",  
  9.       PseudoName = "Yougerthen"  
  10.     });  
  11.     Add(new Person {  
  12.       FirstName = "Bejaoui",  
  13.       LastName = "Bechir",  
  14.       PseudoName = "Yougerthen"  
  15.     });  
  16.     Add(new Person {  
  17.       FirstName = "Bejaoui",  
  18.       LastName = "Bechir",  
  19.       PseudoName = "Yougerthen"  
  20.     });  
  21.   
  22.   }  
  23.   public List < Person > ToList() {  
  24.     return this.ToList < Person > ();  
  25.   }  
Now, let's move to the XAML editor and add an ItemsControl as follow:
  1. < UserControl xmlns: data = "clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data"  
  2. x: Class = "Silverlight.Page"  
  3. xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation"  
  4. xmlns: x = "http://schemas.microsoft.com/winfx/2006/xaml"  
  5. Width = "600"  
  6. Height = "200" > <Grid x: Name = "LayoutRoot"  
  7. MouseEnter = "LayoutRoot_MouseEnter"  
  8. MouseLeave = "LayoutRoot_MouseLeave"  
  9. Background = "Azure" >  
  10.   
  11. <ItemsControl FontSize = "16"  
  12. x: Name = "myItemsControl" > </ItemsControl>  
  13.          
  14.     </Grid > </UserControl>
Then we bind our ItemsControl to the data provided by the "collection" object at the C# code behind the side as follow:
  1. ItemsControl oControl;  
  2. AuthorsCollection collection;  
  3. public Page()  
  4. {  
  5.    InitializeComponent();  
  6.    oControl = LayoutRoot.FindName("myItemsControl"as ItemsControl;  
  7.    collection = new AuthorsCollection();  
  8.    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-
  1. private void LayoutRoot_MouseEnter(object sender, MouseEventArgs e) {  
  2.   collection.Add(new Person {  
  3.     FirstName = "Bejaoui",  
  4.     LastName = "Bechir",  
  5.     PseudoName = "Yougethen"  
  6.   });  
  7.   oItemsControl.ItemsSource = collection.ToList();  
  8. }  
  9. private void LayoutRoot_MouseLeave(object sender, MouseEventArgs e) {  
  10.   collection.RemoveAt(collection.Count - 1);  
  11.   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
  1. public class Person: INotifyPropertyChanged {  
  2.   public Person() {}  
  3.   public Person(string FirstName, string LastName, string PseudoName) {  
  4.     this.FirstName = FirstName;  
  5.     this.LastName = LastName;  
  6.     this.PseudoName = PseudoName;  
  7.   }  
  8.   public string FirstName {  
  9.     get;  
  10.     set;  
  11.   }  
  12.   public string LastName {  
  13.     get;  
  14.     set;  
  15.   }  
  16.   private string _pseudoName;  
  17.   public string PseudoName {  
  18.     get {  
  19.       return _pseudoName;  
  20.     }  
  21.     set {  
  22.       _pseudoName = value;  
  23.       if (PropertyChanged != null) {  
  24.         PropertyChanged(thisnew PropertyChangedEventArgs("PseudoName"));  
  25.       }  
  26.     }  
  27.   }  
  28.   public override string ToString() {  
  29.     return string.Format("First name: {0}, Last name: {1}, Pseudo name: {2}", FirstName, LastName, PseudoName);  
  30.   }#region INotifyPropertyChanged Members  
  31.   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.
  1. private void LayoutRoot_MouseEnter(object sender, MouseEventArgs e) {  
  2.   collection.Add(new Person {  
  3.     FirstName = "Bejaoui",  
  4.     LastName = "Bechir",  
  5.     PseudoName = "Yougerthen"  
  6.   });  
  7.   Person person = collection[0];  
  8.   person.PseudoName = "Sheshonq";  
  9.   oControl.ItemsSource = collection.ToList();  
  10. }  
  11. private void LayoutRoot_MouseLeave(object sender, MouseEventArgs e) {  
  12.   Person person = collection[0];  
  13.   person.PseudoName = "Yougerthen";  
  14.   collection.RemoveAt(collection.Count - 1);  
  15.   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.


Similar Articles