Skip to content

Instantly share code, notes, and snippets.

@mr5z
Created December 26, 2021 14:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mr5z/4404e397437841ad9f2f33fdd5c13093 to your computer and use it in GitHub Desktop.
Save mr5z/4404e397437841ad9f2f33fdd5c13093 to your computer and use it in GitHub Desktop.
Observes both collection changed and items changed.
internal class ObservableCollectionAndItems<TModel> where TModel : INotifyPropertyChanged
{
private readonly ObservableCollection<TModel> collection = new();
public event EventHandler<EventArgs>? ItemChanged;
public event EventHandler<NotifyCollectionChangedEventArgs>? CollectionChanged;
public ObservableCollectionAndItems()
{
collection.CollectionChanged += Collection_CollectionChanged;
}
private void Collection_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
CollectionChanged?.Invoke(sender, e);
}
private void Item_PropertyChanged(object sender, EventArgs e)
{
ItemChanged?.Invoke(sender, e);
}
public void Add(TModel model)
{
model.PropertyChanged += Item_PropertyChanged;
collection.Add(model);
}
public bool Remove(TModel model)
{
model.PropertyChanged -= Item_PropertyChanged;
return collection.Remove(model);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment