This repository was archived by the owner on Jun 21, 2023. It is now read-only.
Repository navigation
Expand file tree
/
Copy pathObservableCollectionExtensions.cs
More file actions
101 lines (89 loc) · 3.26 KB
/
Copy pathObservableCollectionExtensions.cs
File metadata and controls
101 lines (89 loc) · 3.26 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
using System;
using System.Collections;
using System.Collections.Specialized;
namespace GitHub.Extensions
{
public static class ObservableCollectionExtensions
{
/// <summary>
/// Invokes an action for each item in a collection and subsequently each item added or
/// removed from the collection.
/// </summary>
/// <typeparam name="T">The type of the collection items.</typeparam>
/// <param name="collection">The collection.</param>
/// <param name="added">
/// An action called initially for each item in the collection and subsequently for each
/// item added to the collection.
/// </param>
/// <param name="removed">
/// An action called for each item removed from the collection.
/// </param>
/// <param name="reset">
/// An action called when the collection is reset. This will be followed by calls to
/// <paramref name="added"/> for each item present in the collection after the reset.
/// </param>
/// <returns>A disposable used to terminate the subscription.</returns>
public static IDisposable ForEachItem<T>(
this IReadOnlyObservableCollection<T> collection,
Action<T> added,
Action<T> removed,
Action reset)
{
Action<IList> add = items =>
{
foreach (T item in items)
{
added(item);
}
};
Action<IList> remove = items =>
{
for (var i = items.Count - 1; i >= 0; --i)
{
removed((T)items[i]);
}
};
NotifyCollectionChangedEventHandler handler = (_, e) =>
{
switch (e.Action)
{
case NotifyCollectionChangedAction.Add:
add(e.NewItems);
break;
case NotifyCollectionChangedAction.Move:
case NotifyCollectionChangedAction.Replace:
remove(e.OldItems);
add(e.NewItems);
break;
case NotifyCollectionChangedAction.Remove:
remove(e.OldItems);
break;
case NotifyCollectionChangedAction.Reset:
if (reset == null)
{
throw new InvalidOperationException(
"Reset called on collection without reset handler.");
}
reset();
add((IList)collection);
break;
}
};
add((IList)collection);
collection.CollectionChanged += handler;
return new ActionDisposable(() => collection.CollectionChanged -= handler);
}
class ActionDisposable : IDisposable
{
Action dispose;
public ActionDisposable(Action dispose)
{
this.dispose = dispose;
}
public void Dispose()
{
dispose();
}
}
}
}