Blue Theme Orange Theme Green Theme Red Theme
 
Home | Forums | Videos | Photos | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Login Close
User Id:
Password:
 
Forgot Password
Forgot Username
Why Register
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
 Resources  
Close
 Our Network  
Close
Search :       Advanced Search »
Home » .NET 3.0/3.5 » 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:
Total page views :  2424
Total downloads :  34
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
Bejaoui.zip
 
Become a Sponsor


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


Login to add your contents and source code to 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'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.
Go.NET
Build custom interactive diagrams, network, workflow editors, flowcharts, or software design tools. Includes many predefined kinds of nodes, links, and basic shapes. Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-place editing, tooltips, grids, printing, overview window, palette. 100% implemented in C# as a managed .NET Control. Document/View/Tool architecture with many properties&events. Optional automatic layout.
Dundas Software
Dundas Chart for .NET is the most advanced .NET charting package available today.  With an extremely complete feature set, elegant architecture and easy implementation, Dundas Chart can quickly add advanced Charting functionality to enhance and transform ASP.NET and Windows Forms applications.  Whether you are implementing charting into internal projects, or building applications for clients, Dundas Chart offers advanced technology and advanced results to get the most out of data.
Clickatell's SMS Gateway
Clickatell's Developer Solutions allow you to SMS enable any website or application via a range of API's. Learn More about our API connections.
Free access to .NET Memory Management video
Everything you need to know about Garbage Collection, Temporary Objects, Fragmentation, Finalization and common causes of memory leaks in .NET. Watch the video here.
Microsoft Visual Studio 2010 Professional
Microsoft Visual Studio 2010 Professional will launch on April 12, but you can beat the rush and secure your copy today by pre-ordering at the affordable estimated retail price of $549 (US). Pre-order now.
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.
Developer-Ready ASP.NET 2.0 Web Hosting with 3 MONTHS FREE
Now supporting .NET 3.0 Framework with Windows Workflow Foundation, Windows Communication Foundation (WCF), Windows Presentation Foundation (WPF), windows CardSpace (WCS)! Providing more flexibility for Developers with Web Services Support and a User/Permission Manger. Also supporting MS SQL 2005/2000 with Real-Time Backups, FREE Automated Attach .MDF Tool, FREE SQL Restore and Shrink SQL DB Tools, and SQL
 
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
Bejaoui.zip
 
 Post a Feedback, Comment, or Question about this article
Subject:  
Comment:  
Become a Sponsor
 Comments

 Hosted by MaximumASP  |  Found a broken link?  |  Contact Us  |  Terms & conditions  |  Privacy Policy  |  Site Map  |  Suggest an Idea  |  Media Kit
Current Version: 5.2009.6.2
 © 2010  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.