Blue Theme Orange Theme Green Theme Red Theme
 
Discover the top 5 tips for understanding .NET Interop
Home | Forums | Videos | Advertise | Certifications | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
DevExpress UI Controls
Search :       Advanced Search »
Home » Learn .NET » C# and XAML within a Silverlight 2 context - INotifyCollectionChanged implementation: Part V

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

In this article I will demonstrate different techniques of how implement the INotifyCollectionChanged interface as a part of the article how does XAML interact with C#

Author Rank :
Page Views : 5172
Downloads : 54
Rating :
 Rate it
Level : Advanced
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
Bejaoui.zip
 
 
Team Foundation Server Hosting
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 


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!!!

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
Login to add your contents and source code to this article
 [Top] Rate this article
 
 About the author
 
Bechir Bejaoui

The author holds a master degree in NTIC specialized  in software developement delivered by the high school of communication SUPCOM, he also holds a bachelor degree in finance delivered by  the  economic sciences and  management  university of Tunis "FSEGT".

He also holds:

MCPD enteprise solutions developement 3.5 certification and MCTS distibuted application developement 2.0

 He's a freelance developer since 2006. Actually woking on the WPF, .Net framewok 3.5, silverlight and the other .Net new features, in addition, he is painter and sculptor.

Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Discover the Top 5 .NET Memory Management Fundamentals
To write the best .NET code, you need to know exactly how the .NET framework really manages memory. Ricky Leeks presents the Top 5 fundamental facts of .NET memory management. Learn more.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
Discover the top 5 tips for understanding .NET Interop
Become a Sponsor
 Comments
Really Helpful by rbs On January 2, 2011
This was really helpful, I've not been able to find anything so clearly stated - thanks. Ray Starkey
Reply | Email | Modify 
Nevron Chart
 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.