Created
July 30, 2020 08:02
-
-
Save grimorde/733ce3c501a8ad03c16f7570177aae59 to your computer and use it in GitHub Desktop.
Extend the ObservableRangeCollection object to recognise when an item is changed
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections; | |
using System.Collections.Specialized; | |
using System.ComponentModel; | |
using MvvmHelpers; | |
namespace MyApp.Controls | |
{ | |
public class ItemsChangeObservableRangeCollection<T> : | |
ObservableRangeCollection<T> where T : INotifyPropertyChanged | |
{ | |
public delegate void ItemChangedEventHandler(object source, EventArgs args); | |
/// <summary> | |
/// Event fired when an item of the collection is updated | |
/// </summary> | |
public event ItemChangedEventHandler ItemChanged; | |
protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e) | |
{ | |
if (e.Action == NotifyCollectionChangedAction.Add) | |
{ | |
RegisterPropertyChanged(e.NewItems); | |
} | |
else if (e.Action == NotifyCollectionChangedAction.Remove) | |
{ | |
UnRegisterPropertyChanged(e.OldItems); | |
} | |
else if (e.Action == NotifyCollectionChangedAction.Replace) | |
{ | |
UnRegisterPropertyChanged(e.OldItems); | |
RegisterPropertyChanged(e.NewItems); | |
} | |
base.OnCollectionChanged(e); | |
} | |
protected override void ClearItems() | |
{ | |
UnRegisterPropertyChanged(this); | |
base.ClearItems(); | |
} | |
private void RegisterPropertyChanged(IList items) | |
{ | |
foreach (INotifyPropertyChanged item in items) | |
{ | |
if (item != null) | |
{ | |
item.PropertyChanged += new PropertyChangedEventHandler(item_PropertyChanged); | |
} | |
} | |
} | |
private void UnRegisterPropertyChanged(IList items) | |
{ | |
foreach (INotifyPropertyChanged item in items) | |
{ | |
if (item != null) | |
{ | |
item.PropertyChanged -= new PropertyChangedEventHandler(item_PropertyChanged); | |
} | |
} | |
} | |
private void item_PropertyChanged(object sender, PropertyChangedEventArgs e) | |
{ | |
OnItemChange(sender); | |
} | |
protected virtual void OnItemChange(object sender) | |
{ | |
ItemChanged?.Invoke(sender, EventArgs.Empty); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment