Answer to Question #318206 in C# for Collection

Question #318206

Create an Observable Collection. Listen to its Collection Changed Event and



display message on UI for each operation.



1. Addition: “Element ‘x’ is added in collection”



2. Removal: “Element ‘x’ is removed from collection”



Use enum NotifyCollectionChangedAction to differentiate the action

1
Expert's answer
2022-03-25T12:10:31-0400
using System;
using System.Collections.ObjectModel;
using System.Collections.Specialized;


namespace MathApp


{
    class Program
    {


        static void Main()
            {
            ObservableCollection<int> numbers = new ObservableCollection<int>();
            numbers.Add(1);
            numbers.CollectionChanged += OnCollectionchanged;
            numbers.Add(5);
            numbers.Add(10);
            numbers.RemoveAt(0);


        }


        private static void OnCollectionchanged(object sender, NotifyCollectionChangedEventArgs e)
        {
            if (e.Action == NotifyCollectionChangedAction.Add)
                if(e.NewItems?[0] is int newnumber)
                    Console.WriteLine($"Element {newnumber} is added in collection");
            if (e.Action == NotifyCollectionChangedAction.Remove)
                if (e.OldItems?[0] is int oldnumber)
                    Console.WriteLine($"Element {oldnumber} is removed from collection");
        }
    }
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS