/
BindingList.cs
550 lines (447 loc) · 18.9 KB
/
BindingList.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
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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Reflection;
using System.Runtime.CompilerServices;
namespace System.ComponentModel
{
[Serializable]
[TypeForwardedFrom("System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public class BindingList<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] T> :
Collection<T>, IBindingList, ICancelAddNew, IRaiseItemChangedEvents
{
private int addNewPos = -1; // Do not rename (binary serialization)
private bool raiseListChangedEvents = true; // Do not rename (binary serialization)
private bool raiseItemChangedEvents; // Do not rename (binary serialization)
[NonSerialized]
private PropertyDescriptorCollection? _itemTypeProperties;
[NonSerialized]
private PropertyChangedEventHandler? _propertyChangedEventHandler;
[NonSerialized]
private AddingNewEventHandler? _onAddingNew;
[NonSerialized]
private ListChangedEventHandler? _onListChanged;
[NonSerialized]
private int _lastChangeIndex = -1;
private bool allowNew = true; // Do not rename (binary serialization)
private bool allowEdit = true; // Do not rename (binary serialization)
private bool allowRemove = true; // Do not rename (binary serialization)
private bool userSetAllowNew; // Do not rename (binary serialization)
#region Constructors
[RequiresUnreferencedCode("Raises ListChanged events with PropertyDescriptors. PropertyDescriptors require unreferenced code.")]
public BindingList() => Initialize();
/// <summary>
/// Constructor that allows substitution of the inner list with a custom list.
/// </summary>
[RequiresUnreferencedCode("Raises ListChanged events with PropertyDescriptors. PropertyDescriptors require unreferenced code.")]
public BindingList(IList<T> list) : base(list)
{
Initialize();
}
[RequiresUnreferencedCode("Raises ListChanged events with PropertyDescriptors. PropertyDescriptors require unreferenced code.")]
private void Initialize()
{
// Set the default value of AllowNew based on whether type T has a default constructor
allowNew = ItemTypeHasDefaultConstructor;
// Check for INotifyPropertyChanged
if (typeof(INotifyPropertyChanged).IsAssignableFrom(typeof(T)))
{
// Supports INotifyPropertyChanged
raiseItemChangedEvents = true;
// Loop thru the items already in the collection and hook their change notification.
foreach (T item in Items)
{
HookPropertyChanged(item);
}
}
}
private static bool ItemTypeHasDefaultConstructor
{
get
{
Type itemType = typeof(T);
if (itemType.IsPrimitive)
{
return true;
}
const BindingFlags BindingFlags = BindingFlags.Public | BindingFlags.Instance | BindingFlags.CreateInstance;
return itemType.GetConstructor(BindingFlags, null, Type.EmptyTypes, null) != null;
}
}
#endregion
#region AddingNew event
/// <summary>
/// Event that allows a custom item to be provided as the new item added to the list by AddNew().
/// </summary>
public event AddingNewEventHandler AddingNew
{
add
{
bool allowNewWasTrue = AllowNew;
_onAddingNew += value;
if (allowNewWasTrue != AllowNew)
{
FireListChanged(ListChangedType.Reset, -1);
}
}
remove
{
bool allowNewWasTrue = AllowNew;
_onAddingNew -= value;
if (allowNewWasTrue != AllowNew)
{
FireListChanged(ListChangedType.Reset, -1);
}
}
}
/// <summary>
/// Raises the AddingNew event.
/// </summary>
protected virtual void OnAddingNew(AddingNewEventArgs e) => _onAddingNew?.Invoke(this, e);
// Private helper method
private object? FireAddingNew()
{
AddingNewEventArgs e = new AddingNewEventArgs(null);
OnAddingNew(e);
return e.NewObject;
}
#endregion
#region ListChanged event
/// <summary>
/// Event that reports changes to the list or to items in the list.
/// </summary>
public event ListChangedEventHandler ListChanged
{
add => _onListChanged += value;
remove => _onListChanged -= value;
}
/// <summary>
/// Raises the ListChanged event.
/// </summary>
protected virtual void OnListChanged(ListChangedEventArgs e) => _onListChanged?.Invoke(this, e);
public bool RaiseListChangedEvents
{
get => raiseListChangedEvents;
set => raiseListChangedEvents = value;
}
public void ResetBindings() => FireListChanged(ListChangedType.Reset, -1);
public void ResetItem(int position)
{
FireListChanged(ListChangedType.ItemChanged, position);
}
// Private helper method
private void FireListChanged(ListChangedType type, int index)
{
if (raiseListChangedEvents)
{
OnListChanged(new ListChangedEventArgs(type, index));
}
}
#endregion
#region Collection<T> overrides
// Collection<T> funnels all list changes through the four virtual methods below.
// We override these so that we can commit any pending new item and fire the proper ListChanged events.
protected override void ClearItems()
{
EndNew(addNewPos);
if (raiseItemChangedEvents)
{
foreach (T item in Items)
{
UnhookPropertyChanged(item);
}
}
base.ClearItems();
FireListChanged(ListChangedType.Reset, -1);
}
[UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:RequiresUnreferencedCode",
Justification = "BindingList ctor is marked with RequiresUnreferencedCode.")]
protected override void InsertItem(int index, T item)
{
EndNew(addNewPos);
base.InsertItem(index, item);
if (raiseItemChangedEvents)
{
HookPropertyChanged(item);
}
FireListChanged(ListChangedType.ItemAdded, index);
}
protected override void RemoveItem(int index)
{
// Need to all RemoveItem if this on the AddNew item
if (!allowRemove && !(addNewPos >= 0 && addNewPos == index))
{
throw new NotSupportedException();
}
EndNew(addNewPos);
if (raiseItemChangedEvents)
{
UnhookPropertyChanged(this[index]);
}
base.RemoveItem(index);
FireListChanged(ListChangedType.ItemDeleted, index);
}
[UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:RequiresUnreferencedCode",
Justification = "BindingList ctor is marked with RequiresUnreferencedCode.")]
protected override void SetItem(int index, T item)
{
if (raiseItemChangedEvents)
{
UnhookPropertyChanged(this[index]);
}
base.SetItem(index, item);
if (raiseItemChangedEvents)
{
HookPropertyChanged(item);
}
FireListChanged(ListChangedType.ItemChanged, index);
}
#endregion
#region ICancelAddNew interface
/// <summary>
/// If item added using AddNew() is still cancellable, then remove that item from the list.
/// </summary>
public virtual void CancelNew(int itemIndex)
{
if (addNewPos >= 0 && addNewPos == itemIndex)
{
RemoveItem(addNewPos);
addNewPos = -1;
}
}
/// <summary>
/// If item added using AddNew() is still cancellable, then commit that item.
/// </summary>
public virtual void EndNew(int itemIndex)
{
if (addNewPos >= 0 && addNewPos == itemIndex)
{
addNewPos = -1;
}
}
#endregion
#region IBindingList interface
/// <summary>
/// Adds a new item to the list. Calls <see cref="AddNewCore" /> to create and add the item.
///
/// Add operations are cancellable via the <see cref="ICancelAddNew" /> interface. The position of the
/// new item is tracked until the add operation is either cancelled by a call to <see cref="CancelNew" />,
/// explicitly committed by a call to <see cref="EndNew" />, or implicitly commmited some other operation
/// changes the contents of the list (such as an Insert or Remove). When an add operation is
/// cancelled, the new item is removed from the list.
/// </summary>
public T AddNew() => (T)((this as IBindingList).AddNew())!;
object? IBindingList.AddNew()
{
// Create new item and add it to list
object? newItem = AddNewCore();
// Record position of new item (to support cancellation later on)
addNewPos = (newItem != null) ? IndexOf((T)newItem) : -1;
// Return new item to caller
return newItem;
}
private bool AddingNewHandled => _onAddingNew != null && _onAddingNew.GetInvocationList().Length > 0;
/// <summary>
/// Creates a new item and adds it to the list.
///
/// The base implementation raises the AddingNew event to allow an event handler to
/// supply a custom item to add to the list. Otherwise an item of type T is created.
/// The new item is then added to the end of the list.
/// </summary>
protected virtual object? AddNewCore()
{
// Allow event handler to supply the new item for us
// If event handler did not supply new item, create one ourselves
object? newItem = FireAddingNew() ?? Activator.CreateInstance(typeof(T));
// Add item to end of list. Note: If event handler returned an item not of type T,
// the cast below will trigger an InvalidCastException. This is by design.
Add((T)newItem!);
// Return new item to caller
return newItem;
}
public bool AllowNew
{
get
{
// If the user set AllowNew, return what they set. If we have a default constructor, allowNew will be
// true and we should just return true.
if (userSetAllowNew || allowNew)
{
return allowNew;
}
// Even if the item doesn't have a default constructor, the user can hook AddingNew to provide an item.
// If there's a handler for this, we should allow new.
return AddingNewHandled;
}
set
{
bool oldAllowNewValue = AllowNew;
userSetAllowNew = true;
// Note that we don't want to set allowNew only if AllowNew didn't match value,
// since AllowNew can depend on onAddingNew handler
allowNew = value;
if (oldAllowNewValue != value)
{
FireListChanged(ListChangedType.Reset, -1);
}
}
}
bool IBindingList.AllowNew => AllowNew;
public bool AllowEdit
{
get => allowEdit;
set
{
if (allowEdit != value)
{
allowEdit = value;
FireListChanged(ListChangedType.Reset, -1);
}
}
}
bool IBindingList.AllowEdit => AllowEdit;
public bool AllowRemove
{
get => allowRemove;
set
{
if (allowRemove != value)
{
allowRemove = value;
FireListChanged(ListChangedType.Reset, -1);
}
}
}
bool IBindingList.AllowRemove => AllowRemove;
bool IBindingList.SupportsChangeNotification => SupportsChangeNotificationCore;
protected virtual bool SupportsChangeNotificationCore => true;
bool IBindingList.SupportsSearching => SupportsSearchingCore;
protected virtual bool SupportsSearchingCore => false;
bool IBindingList.SupportsSorting => SupportsSortingCore;
protected virtual bool SupportsSortingCore => false;
bool IBindingList.IsSorted => IsSortedCore;
protected virtual bool IsSortedCore => false;
PropertyDescriptor? IBindingList.SortProperty => SortPropertyCore;
protected virtual PropertyDescriptor? SortPropertyCore => null;
ListSortDirection IBindingList.SortDirection => SortDirectionCore;
protected virtual ListSortDirection SortDirectionCore => ListSortDirection.Ascending;
void IBindingList.ApplySort(PropertyDescriptor prop, ListSortDirection direction)
{
ApplySortCore(prop, direction);
}
protected virtual void ApplySortCore(PropertyDescriptor prop, ListSortDirection direction)
{
throw new NotSupportedException();
}
void IBindingList.RemoveSort() => RemoveSortCore();
protected virtual void RemoveSortCore()
{
throw new NotSupportedException();
}
int IBindingList.Find(PropertyDescriptor prop, object key) => FindCore(prop, key);
protected virtual int FindCore(PropertyDescriptor prop, object key)
{
throw new NotSupportedException();
}
void IBindingList.AddIndex(PropertyDescriptor prop)
{
// Not supported
}
void IBindingList.RemoveIndex(PropertyDescriptor prop)
{
// Not supported
}
#endregion
#region Property Change Support
[RequiresUnreferencedCode("Raises ListChanged events with PropertyDescriptors. PropertyDescriptors require unreferenced code.")]
private void HookPropertyChanged(T item)
{
// Note: inpc may be null if item is null, so always check.
if (item is INotifyPropertyChanged inpc)
{
_propertyChangedEventHandler ??= new PropertyChangedEventHandler(Child_PropertyChanged);
inpc.PropertyChanged += _propertyChangedEventHandler;
}
}
private void UnhookPropertyChanged(T item)
{
// Note: inpc may be null if item is null, so always check.
if (item is INotifyPropertyChanged inpc && _propertyChangedEventHandler != null)
{
inpc.PropertyChanged -= _propertyChangedEventHandler;
}
}
[RequiresUnreferencedCode("Raises ListChanged events with PropertyDescriptors. PropertyDescriptors require unreferenced code.")]
private void Child_PropertyChanged(object? sender, PropertyChangedEventArgs? e)
{
if (RaiseListChangedEvents)
{
if (sender == null || e == null || string.IsNullOrEmpty(e.PropertyName))
{
// Fire reset event (per INotifyPropertyChanged spec)
ResetBindings();
}
else
{
// The change event is broken should someone pass an item to us that is not
// of type T. Still, if they do so, detect it and ignore. It is an incorrect
// and rare enough occurrence that we do not want to slow the mainline path
// with "is" checks.
T item;
try
{
item = (T)sender;
}
catch (InvalidCastException)
{
ResetBindings();
return;
}
// Find the position of the item. This should never be -1. If it is,
// somehow the item has been removed from our list without our knowledge.
int pos = _lastChangeIndex;
if (pos < 0 || pos >= Count || !this[pos]!.Equals(item))
{
pos = IndexOf(item);
_lastChangeIndex = pos;
}
if (pos == -1)
{
// The item was removed from the list but we still get change notifications or
// the sender is invalid and was never added to the list.
UnhookPropertyChanged(item);
ResetBindings();
}
else
{
// Get the property descriptor
if (null == _itemTypeProperties)
{
// Get Shape
_itemTypeProperties = TypeDescriptor.GetProperties(typeof(T));
Debug.Assert(_itemTypeProperties != null);
}
PropertyDescriptor? pd = _itemTypeProperties.Find(e.PropertyName, true);
// Create event args. If there was no matching property descriptor,
// we raise the list changed anyway.
ListChangedEventArgs args = new ListChangedEventArgs(ListChangedType.ItemChanged, pos, pd);
// Fire the ItemChanged event
OnListChanged(args);
}
}
}
}
#endregion
#region IRaiseItemChangedEvents interface
/// <summary>
/// Returns false to indicate that BindingList<T> does NOT raise ListChanged events
/// of type ItemChanged as a result of property changes on individual list items
/// unless those items support INotifyPropertyChanged.
/// </summary>
bool IRaiseItemChangedEvents.RaisesItemChangedEvents => raiseItemChangedEvents;
#endregion
}
}