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

In the previous article how does C# code behind interact with an XAML interface within a Silverlight 2 context? - INotifyPropertyChanged implementation: Part IV, I gave an example of how to use C# code to implement notification mechanism so that if a 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 an XAML interface interact with C# code behind within a Silverlight 2 context? -Introduction-Part I, which is: What if an objects list or collection is changed during the application process, how does the control (XAML side) know that changes are happen 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 objects collection and not a single object property? In this case, the INotifyPropertyChanged is not sufficient to leverage a complete notification process. Therefore, the Silverlight 2 provides to 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 new 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 the both mouse enter and mouse leave event handlers' stubs in the code behind as follow:

private void LayoutRoot_MouseEnter(object sender, MouseEventArgs e)
{
  collection.Add(new Person {FirstName="Bejaoui",
                             LastName="Bechir",
                             PseudoName="Yougerthen" });
            oControl.ItemsSource = collection;
}

private void LayoutRoot_MouseLeave(object sender, MouseEventArgs e)
{
  collection.RemoveAt(collection.Count -1);
  oControl.ItemsSource = collection;
}


Finally, let's fire up the application and observeNow, if the mouse enters the grid zone will looks like



Figure 1

And if the mouse leaves the grid zone will looks 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 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
    {

         /* TO DO: we implement the code that adds and removes data
         * without forgetting to notify the target XAML object so that
         * data display will be changed if any changes happens 
        
*/
        #region INotifyCollectionChanged Members

        public event NotifyCollectionChangedEventHandler CollectionChanged
        #endregion
    }

At 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
{

 /// <summary>
 /// void: Method that enables add a person to
 /// the list
 /// </summary>
 /// <param name="person">Person: Person going to be added</param>
 protected void Add(Person person)
 {
  base.Add(person);
  if (CollectionChanged != null)
  {
   CollectionChanged(this, new
NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add));
  }
 }
 /// <summary>
 /// void: Method that enables remove a person from
 /// the list
 /// </summary>
 /// <param name="person">Person: Person going to be removed</param>
 protected void Remove(Person person)
 {
  base.RemoveAt(this.IndexOf(person));
  if (CollectionChanged != null)
  {
  CollectionChanged(this, new
NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove));
  }
 }
 /// <summary>
 /// event: The INotifyCollectionChanged member
 /// </summary>
#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:

      
/// <summary>
    /// This class inherits the PersonCollection
    /// </summary>
    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 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 happens at the properties' levels of a given element within the list.

To combine the both implementations let's do some rectifications to the Person classpublic

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 pervious article series how does C# code behind interact with an 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 the mouse events.

That's it.

Good Dotneting!!!

 

Next Recommended Readings