Observable Collection Of T Example

The ObservableCollection<T> collection class is a generic class that can provide a notification of something has been added to the list, removed from the list, or the list was refreshed. This notification is done via event handlers which I’ll demonstrate.

ObsCollectionSolution ObsCollectionProgram

 
Program.cs Code Contents

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections.ObjectModel;
using System.Collections.Specialized;

namespace ObsCollOfT
{
    class Program
    {
        /// <summary>
        /// Demonstrating the ObservableCollection<T> collection class.
        /// </summary>
        /// <param name="args"></param>

        static void Main(string[] args)
        {
            // Let's first create an observable collection.
            var presidents = createPresidents();

            // Subscribing to an event handler that watches for changes in the Observable collection.
            Console.WriteLine("****Things That Were Done To ObservableCollection****");
            presidents.CollectionChanged += presidents_CollectionChanged;

            // Now let's add some more presidents to the collection.
            presidents.Add("Bill Clinton");
            
            // Now let's try and remove a president.
            presidents.Remove("Jimmy Carter");

            // Display the collection item.
            Console.WriteLine();
            Console.WriteLine("****Items In The Collection****");
            foreach (string name in presidents)
            {
                Console.WriteLine(name);
            }

            Console.ReadLine();
        }

        private static ObservableCollection<string> createPresidents()
        {
            ObservableCollection<string> presidents = new ObservableCollection<string>
            {
                "Jimmy Carter",
                "Ronald Reagan",
                "George HW Bush"
            };
            return presidents;
        }

        static void presidents_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
        {
            List<string> items = new List<string>();

            if(e.NewItems != null)
            {
                items.AddRange(e.NewItems.OfType<string>());
                foreach (var itemAdded in items)
                {
                    Console.WriteLine("Item Added: {0}", itemAdded);
                }
            }

            if (e.OldItems != null)
            {
                items.AddRange(e.OldItems.OfType<string>());
                foreach (var itemRemoved in items)
                {
                    Console.WriteLine("Item Removed: {0}", itemRemoved);
                }
            }
        }
    }
}

 
I’m trying to seperate things into methods here to keep things from getting too monolithic and keep things simple. I’m creating a variable to hold a ObservableCollection of a list of Presidents.

Next I create a presidents_CollectionChanged event handler method to notify when an item is added or removed from the collection.

Next I’m adding more presidents to the collection to test and see if the event handler will display the notifications.

Then I’ll iterate thru the collection and displaying the element names.

Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s