-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathViewModelObservableCollection.cs
72 lines (64 loc) · 2.03 KB
/
ViewModelObservableCollection.cs
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
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Linq;
namespace bagpipe {
class ViewModelObservableCollection<TViewModel, TModel> : ObservableCollection<TViewModel> {
private readonly ObservableCollection<TModel> source;
private readonly Func<TModel, TViewModel> factory;
public ViewModelObservableCollection(
ObservableCollection<TModel> source,
Func<TModel, TViewModel> factory
) : base(source.Select(x => factory(x))) {
this.source = source;
this.factory = factory;
this.source.CollectionChanged += Source_CollectionChanged;
}
private void Source_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) {
void AddNewItems() {
for (int i = 0; i < e.NewItems.Count; i++) {
Insert(e.NewStartingIndex + i, factory((TModel)e.NewItems[i]));
}
}
void RemoveOldItems() {
for (int i = 0; i < e.OldItems.Count; i++) {
RemoveAt(e.OldStartingIndex);
}
}
switch (e.Action) {
case NotifyCollectionChangedAction.Add: {
AddNewItems();
break;
}
case NotifyCollectionChangedAction.Remove: {
RemoveOldItems();
break;
}
case NotifyCollectionChangedAction.Replace: {
RemoveOldItems();
AddNewItems();
break;
}
case NotifyCollectionChangedAction.Move: {
List<TViewModel> items = this.Skip(e.OldStartingIndex).Take(e.OldItems.Count).ToList();
RemoveOldItems();
// Can't adapt AddNewItems since we don't want to use the factory
for (int i = 0; i < items.Count; i++) {
Insert(e.NewStartingIndex + i, items[i]);
}
break;
}
case NotifyCollectionChangedAction.Reset: {
Clear();
if (e.NewItems != null) {
AddNewItems();
}
break;
}
default:
break;
}
}
}
}