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
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");
}
}
}
Comments
Leave a comment