/
ItemsControl.cs
1174 lines (1002 loc) · 34 KB
/
ItemsControl.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
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Uno.Extensions;
using Uno.UI;
using System.Collections.Specialized;
using Uno.Disposables;
using Uno.UI.Controls;
using Windows.UI.Xaml.Markup;
using Uno.UI.DataBinding;
using Windows.UI.Xaml.Data;
using Windows.Foundation.Collections;
using Uno.Extensions.Specialized;
using Microsoft.Extensions.Logging;
using Uno.UI.Extensions;
using System.ComponentModel;
#if XAMARIN_ANDROID
using View = Android.Views.View;
using _ViewGroup = Android.Views.ViewGroup;
using Font = Android.Graphics.Typeface;
using Android.Graphics;
#elif XAMARIN_IOS
using View = UIKit.UIView;
using _ViewGroup = UIKit.UIView;
using Color = UIKit.UIColor;
using Font = UIKit.UIFont;
using UIKit;
#else
using Color = System.Drawing.Color;
using View = Windows.UI.Xaml.UIElement;
#endif
namespace Windows.UI.Xaml.Controls
{
[ContentProperty(Name = "Items")]
public partial class ItemsControl : Control, IItemsControl
{
private ItemsPresenter _itemsPresenter;
private SerialDisposable _notifyCollectionChanged = new SerialDisposable();
private readonly SerialDisposable _notifyCollectionGroupsChanged = new SerialDisposable();
private bool _isReady; // Template applied
private bool _needsUpdateItems;
// This gets prepended to MaterializedContainers to ensure it's being considered
// even if it might not yet have be added to the ItemsPanel (e.eg., NativeListViewBase).
private DependencyObject _containerBeingPrepared;
private int[] _groupCounts;
/// <summary>
/// This template is stored here in order to allow for
/// FrameworkTemplate pooling to function properly when an ItemTemplateSelector has been
/// specified.
/// </summary>
private readonly static DataTemplate InnerContentPresenterTemplate = new DataTemplate(() => new ContentPresenter());
public static ItemsControl GetItemsOwner(DependencyObject element)
{
// ItemsControl is provided ONLY for the ItemsHost panel
// Neither the ItemsPresenter nor an item container will give a non null result.
var panel = element as Panel;
if (panel != null && panel.IsItemsHost)
{
return panel.ItemsOwner;
}
else
{
return null;
}
}
public ItemsControl()
{
Initialize();
}
void Initialize()
{
InitializePartial();
OnDisplayMemberPathChangedPartial(string.Empty, this.DisplayMemberPath);
}
partial void InitializePartial();
partial void RequestLayoutPartial();
partial void RemoveViewPartial(View current);
private View _internalItemsPanelRoot;
/// <summary>
/// The actual View that acts as the ItemsPanelRoot (used by FlipView and ListView, which don't use actual Panels)
/// </summary>
internal View InternalItemsPanelRoot
{
get { return _internalItemsPanelRoot; }
set
{
if(_internalItemsPanelRoot is IDependencyObjectStoreProvider provider)
{
provider.SetParent(null);
}
_internalItemsPanelRoot = value;
}
}
private Panel _itemsPanelRoot;
public Panel ItemsPanelRoot
{
get { return _itemsPanelRoot; }
set
{
if (_itemsPanelRoot is IDependencyObjectStoreProvider provider)
{
provider.SetParent(null);
}
_itemsPanelRoot = value;
}
}
/// <summary>
/// True if ItemsControl should manage the children of ItemsPanel, false if this is handled by an inheriting class.
/// </summary>
private bool ShouldItemsControlManageChildren { get { return ItemsPanelRoot == InternalItemsPanelRoot; } }
#region ItemsPanel DependencyProperty
public ItemsPanelTemplate ItemsPanel
{
get { return (ItemsPanelTemplate)GetValue(ItemsPanelProperty); }
set { SetValue(ItemsPanelProperty, value); }
}
public static DependencyProperty ItemsPanelProperty =
DependencyProperty.Register(
"ItemsPanel",
typeof(ItemsPanelTemplate),
typeof(ItemsControl),
new PropertyMetadata(
(ItemsPanelTemplate)null,
(s, e) => ((ItemsControl)s)?.OnItemsPanelChanged((ItemsPanelTemplate)e.OldValue, (ItemsPanelTemplate)e.NewValue)
)
);
private void OnItemsPanelChanged(ItemsPanelTemplate oldItemsPanel, ItemsPanelTemplate newItemsPanel)
{
if (_isReady) // Panel is created on ApplyTemplate, so do not create it twice (first on set PanelTemplate, second on ApplyTemplate)
{
UpdateItemsPanelRoot();
}
}
#endregion
#region ItemTemplate DependencyProperty
public DataTemplate ItemTemplate
{
get { return (DataTemplate)GetValue(ItemTemplateProperty); }
set { SetValue(ItemTemplateProperty, value); }
}
public static DependencyProperty ItemTemplateProperty =
DependencyProperty.Register(
"ItemTemplate",
typeof(DataTemplate),
typeof(ItemsControl),
new PropertyMetadata(
(DataTemplate)null,
(s, e) => ((ItemsControl)s)?.OnItemTemplateChanged((DataTemplate)e.OldValue, (DataTemplate)e.NewValue)
)
);
protected virtual void OnItemTemplateChanged(DataTemplate oldItemTemplate, DataTemplate newItemTemplate)
{
SetNeedsUpdateItems();
}
#endregion
#region ItemTemplateSelector DependencyProperty
public DataTemplateSelector ItemTemplateSelector
{
get { return (DataTemplateSelector)GetValue(ItemTemplateSelectorProperty); }
set { SetValue(ItemTemplateSelectorProperty, value); }
}
public static DependencyProperty ItemTemplateSelectorProperty =
DependencyProperty.Register(
"ItemTemplateSelector",
typeof(DataTemplateSelector),
typeof(ItemsControl),
new PropertyMetadata(
(DataTemplateSelector)null,
(s, e) => ((ItemsControl)s)?.OnItemTemplateSelectorChanged((DataTemplateSelector)e.OldValue, (DataTemplateSelector)e.NewValue)
)
);
protected virtual void OnItemTemplateSelectorChanged(DataTemplateSelector oldItemTemplateSelector, DataTemplateSelector newItemTemplateSelector)
{
SetNeedsUpdateItems();
}
#endregion
#region ItemsSource DependencyProperty
public object ItemsSource
{
get { return (object)this.GetValue(ItemsSourceProperty); }
set { this.SetValue(ItemsSourceProperty, value); }
}
public static readonly DependencyProperty ItemsSourceProperty =
DependencyProperty.Register(
"ItemsSource",
typeof(object),
typeof(ItemsControl),
new PropertyMetadata(null, (s, e) => ((ItemsControl)s).OnItemsSourceChanged(e))
);
#endregion
private ItemCollection _items;
//TODO: this should reflect the content of ItemsSource, if that property is set. For now, it only exists for setting ItemsControl's contents in xaml.
public ItemCollection Items
{
get { return _items; }
set
{
_items = value;
SetNeedsUpdateItems();
OnItemsChanged();
}
}
internal virtual void OnItemsChanged() { }
/// <summary>
/// The number of groups in the <see cref="ItemsSource"/>, zero if it is ungrouped.
/// </summary>
internal int NumberOfGroups => CollectionGroups?.Count ?? 0;
internal int NumberOfDisplayGroups
{
get
{
if (!AreEmptyGroupsHidden)
{
return NumberOfGroups;
}
return CollectionGroups.Where(g => (g as ICollectionViewGroup).GroupItems.Count > 0).Count();
}
}
/// <summary>
/// The number of items in the source.
/// </summary>
internal int NumberOfItems
{
get
{
var items = GetItems();
if (items is ICollection<object> list)
{
// ICollectionView optimization
return list.Count;
}
return items?.Count() ?? 0;
}
}
internal bool HasItems
{
get
{
var items = GetItems();
if (items is ICollection<object> collection)
{
// ICollectionView optimization
return collection.Count > 0;
}
return items?.Any() ?? false;
}
}
//Return either the contents of ItemsSource or of Items. This method will be obsolete when Items' contents properly reflect ItemsSource
internal IEnumerable GetItems()
{
if (ItemsSource != null)
{
return ItemsSource as IEnumerable;
}
if (Items?.Any() ?? false)
{
return Items;
}
return null;
}
#region ItemContainerStyle DependencyProperty
public Style ItemContainerStyle
{
get { return (Style)GetValue(ItemContainerStyleProperty); }
set { SetValue(ItemContainerStyleProperty, value); }
}
public static readonly DependencyProperty ItemContainerStyleProperty =
DependencyProperty.Register("ItemContainerStyle", typeof(Style), typeof(ItemsControl), new PropertyMetadata(
default(Style),
(o, e) => ((ItemsControl)o).OnItemContainerStyleChanged((Style)e.OldValue, (Style)e.NewValue))
);
protected virtual void OnItemContainerStyleChanged(Style oldItemContainerStyle, Style newItemContainerStyle) { }
#endregion
#region ItemContainerStyleSelector DependencyProperty
public StyleSelector ItemContainerStyleSelector
{
get { return (StyleSelector)GetValue(ItemContainerStyleSelectorProperty); }
set { SetValue(ItemContainerStyleSelectorProperty, value); }
}
public static readonly DependencyProperty ItemContainerStyleSelectorProperty =
DependencyProperty.Register("ItemContainerStyleSelector", typeof(StyleSelector), typeof(ItemsControl), new PropertyMetadata(
default(StyleSelector),
(o, e) => ((ItemsControl)o).OnItemContainerStyleSelectorChanged((StyleSelector)e.OldValue, (StyleSelector)e.NewValue))
);
protected virtual void OnItemContainerStyleSelectorChanged(StyleSelector oldItemContainerStyleSelector, StyleSelector newItemContainerStyleSelector) { }
#endregion
public IObservableVector<GroupStyle> GroupStyle { get; } = new ObservableVector<GroupStyle>();
#region IsGrouping DependencyProperty
public bool IsGrouping
{
get { return (bool)GetValue(IsGroupingProperty); }
private set { SetValue(IsGroupingProperty, value); }
}
public static readonly DependencyProperty IsGroupingProperty =
DependencyProperty.Register("IsGrouping", typeof(bool), typeof(ItemsControl), new PropertyMetadata(false));
#endregion
#region Internal Attached Properties
internal static readonly DependencyProperty IndexForItemContainerProperty =
DependencyProperty.RegisterAttached(
"IndexForItemContainer",
typeof(int),
typeof(ItemsControl),
new PropertyMetadata(-1)
);
internal static readonly DependencyProperty ItemsControlForItemContainerProperty =
DependencyProperty.RegisterAttached(
"ItemsControlForItemContainer",
typeof(WeakReference<ItemsControl>),
typeof(ItemsControl),
new PropertyMetadata(DependencyProperty.UnsetValue)
);
#endregion
internal bool AreEmptyGroupsHidden => CollectionGroups != null && (GroupStyle.FirstOrDefault()?.HidesIfEmpty ?? false);
private IObservableVector<object> CollectionGroups => (GetItems() as ICollectionView)?.CollectionGroups;
internal GroupStyle GetGroupStyle()
{
return GroupStyle.FirstOrDefault();
}
/// <summary>
/// Get the index for the next item after <paramref name="currentItem"/>.
/// </summary>
internal IndexPath? GetNextItemIndex(IndexPath? currentItem, int direction)
{
if (!HasItems)
{
return null;
}
if (currentItem == null)
{
// Null is treated as 'just before the first item.'
if (direction == 1)
{
var firstNonEmptySection = IsGrouping ? GetNextNonEmptySection(-1, 1).Value : 0;
return IndexPath.FromRowSection(0, firstNonEmptySection);
}
else
{
return null;
}
}
if (direction == 1)
{
return GetIncrementedItemIndex(currentItem.Value);
}
if (direction == -1)
{
return GetDecrementedItemIndex(currentItem.Value);
}
throw new ArgumentOutOfRangeException(nameof(direction));
}
private IndexPath? GetIncrementedItemIndex(IndexPath currentItem)
{
if (!IsGrouping)
{
if (currentItem.Section > 0)
{
throw new InvalidOperationException("Received an index with non-zero group, but source is not grouped.");
}
if (currentItem.Row == NumberOfItems - 1)
{
return null;
}
return IndexPath.FromRowSection(currentItem.Row + 1, 0);
}
if (currentItem.Row == GetDisplayGroupCount(currentItem.Section) - 1)
{
var nextSection = GetNextNonEmptySection(currentItem.Section, 1);
if (!nextSection.HasValue)
{
//No more non-empty sections
return null;
}
return IndexPath.FromRowSection(0, nextSection.Value);
}
return IndexPath.FromRowSection(currentItem.Row + 1, currentItem.Section);
}
private IndexPath? GetDecrementedItemIndex(IndexPath currentItem)
{
if (!IsGrouping)
{
if (currentItem.Section > 0)
{
throw new InvalidOperationException("Received an index with non-zero group, but source is not grouped.");
}
if (currentItem.Row == 0)
{
return null;
}
return IndexPath.FromRowSection(currentItem.Row - 1, 0);
}
if (currentItem.Row == 0)
{
var nextSection = GetNextNonEmptySection(currentItem.Section, -1);
if (!nextSection.HasValue)
{
//No previous non-empty sections
return null;
}
return IndexPath.FromRowSection(GetDisplayGroupCount(nextSection.Value) - 1, nextSection.Value);
}
return IndexPath.FromRowSection(currentItem.Row - 1, currentItem.Section);
}
/// <summary>
/// Gets a flattened item index. Unlike <see cref="GetDisplayIndexFromIndexPath(IndexPath)"/>, this can not be overridden to adjust for
/// supplementary elements (eg headers) on derived controls. This represents the (flattened) index in the data source as opposed
/// to the 'display' index.
///
/// Note that the <see cref="IndexPath"/> is still the 'display' value in that it doesn't 'know about' empty groups if HidesIfEmpty is set to true.
/// </summary>
internal int GetIndexFromIndexPath(IndexPath indexPath)
{
if (indexPath.Section == 0)
{
return indexPath.Row;
}
var itemsInPrecedingSections = 0;
for (int i = 0; i < indexPath.Section; i++)
{
itemsInPrecedingSections += GetDisplayGroupCount(i);
}
return itemsInPrecedingSections + indexPath.Row;
}
/// <summary>
/// Convert flat item index to (group, index in group)
/// </summary>
internal IndexPath? GetIndexPathFromIndex(int index)
{
if (!IsGrouping)
{
return IndexPath.FromRowSection(index, 0);
}
int row = index;
for (int i = 0; i < NumberOfDisplayGroups; i++)
{
var groupCount = GetDisplayGroupCount(i);
if (row < groupCount)
{
return IndexPath.FromRowSection(row, i);
}
else
{
row -= groupCount;
}
}
return null;
}
private int? GetNextNonEmptySection(int startingSection, int direction)
{
var i = startingSection;
i += direction;
while (i >= 0 && i < NumberOfDisplayGroups)
{
if (GetDisplayGroupCount(i) > 0)
{
return i;
}
i += direction;
}
return null;
}
/// <summary>
/// Get the last item in the source, or null if the source is empty.
/// </summary>
internal IndexPath? GetLastItem()
{
if (!IsGrouping)
{
var itemCount = NumberOfItems;
if (itemCount <= 0)
{
return null;
}
return IndexPath.FromRowSection(itemCount - 1, 0);
}
for (int i = NumberOfDisplayGroups - 1; i >= 0; i--)
{
var count = GetDisplayGroupCount(i);
if (count > 0)
{
return IndexPath.FromRowSection(count - 1, i);
}
}
// No non-empty groups
return null;
}
/// <summary>
/// Return the index of a group in the unfiltered source, adjusted for empty groups hidden from the view by GroupStyle.HidesIfEmpty=true
/// </summary>
internal int AdjustGroupIndexForHidesIfEmpty(int index)
{
var adjustedIndex = index;
if (AreEmptyGroupsHidden)
{
for (int i = 0; i < index; i++)
{
if (GetGroupCount(i) == 0)
{
adjustedIndex--;
}
}
}
return adjustedIndex;
}
/// <summary>
/// Return the number of items to show on the last line of a group, if there are multiple items per line.
/// </summary>
internal int GetItemsOnLastLine(int section, int itemsPerLine)
{
int remainder = GetDisplayGroupCount(section) % itemsPerLine;
return remainder == 0 ? itemsPerLine : remainder;
}
protected virtual void OnItemsSourceChanged(DependencyPropertyChangedEventArgs e)
{
Items?.Clear();
IsGrouping = (e.NewValue as ICollectionView)?.CollectionGroups != null;
SetNeedsUpdateItems();
ObserveCollectionChanged();
}
internal int GetGroupCount(int groupIndex) => IsGrouping ? GetGroupAt(groupIndex).GroupItems.Count : 0;
internal int GetDisplayGroupCount(int displaySection) => IsGrouping ? GetGroupAtDisplaySection(displaySection).GroupItems.Count : 0;
internal void ObserveCollectionChanged()
{
//Subscribe to changes on grouped source that is an observable collection
if (ItemsSource is CollectionView collectionView && collectionView.CollectionGroups != null && collectionView.InnerCollection is INotifyCollectionChanged observableGroupedSource)
{
// This is a workaround for a bug with EventRegistrationTokenTable on Xamarin, where subscribing/unsubscribing to a class method directly won't
// remove the handler.
NotifyCollectionChangedEventHandler handler = OnItemsSourceGroupsChanged;
_notifyCollectionChanged.Disposable = Disposable.Create(() =>
observableGroupedSource.CollectionChanged -= handler
);
observableGroupedSource.CollectionChanged += handler;
}
//Subscribe to changes on ICollectionView that is grouped
else if (ItemsSource is ICollectionView iCollectionView && iCollectionView.CollectionGroups != null)
{
// This is a workaround for a bug with EventRegistrationTokenTable on Xamarin, where subscribing/unsubscribing to a class method directly won't
// remove the handler.
VectorChangedEventHandler<object> handler = OnItemsSourceGroupsVectorChanged;
_notifyCollectionChanged.Disposable = Disposable.Create(() =>
iCollectionView.CollectionGroups.VectorChanged -= handler
);
iCollectionView.CollectionGroups.VectorChanged += handler;
}
//Subscribe to changes on observable collection
else if (ItemsSource is INotifyCollectionChanged existingObservable)
{
// This is a workaround for a bug with EventRegistrationTokenTable on Xamarin, where subscribing/unsubscribing to a class method directly won't
// remove the handler.
NotifyCollectionChangedEventHandler handler = OnItemsSourceCollectionChanged;
_notifyCollectionChanged.Disposable = Disposable.Create(() =>
existingObservable.CollectionChanged -= handler
);
existingObservable.CollectionChanged += handler;
}
else if (ItemsSource is IObservableVector<object> observableVector)
{
// This is a workaround for a bug with EventRegistrationTokenTable on Xamarin, where subscribing/unsubscribing to a class method directly won't
// remove the handler.
VectorChangedEventHandler<object> handler = OnItemsSourceVectorChanged;
_notifyCollectionChanged.Disposable = Disposable.Create(() =>
observableVector.VectorChanged -= handler
);
observableVector.VectorChanged += handler;
}
else
{
_notifyCollectionChanged.Disposable = null;
}
_notifyCollectionGroupsChanged.Disposable = null;
//Subscribe to group changes if they are observable collections
if (ItemsSource is ICollectionView collectionViewGrouped && collectionViewGrouped.CollectionGroups != null)
{
var disposables = new CompositeDisposable();
int i = -1;
foreach (ICollectionViewGroup group in collectionViewGrouped.CollectionGroups)
{
//Hidden empty groups shouldn't be counted because they won't appear to UICollectionView
if (!AreEmptyGroupsHidden || group.GroupItems.Count > 0)
{
i++;
}
var insideLoop = i;
// TODO: At present we listen to changes on ICollectionViewGroup.Group, which supports 'observable of observable groups'
// using CollectionViewSource. The correct way to do this would be for CollectionViewGroup.GroupItems to instead implement
// INotifyCollectionChanged.
INotifyCollectionChanged observableGroup = group.GroupItems as INotifyCollectionChanged ?? group.Group as INotifyCollectionChanged;
// Prefer INotifyCollectionChanged for, eg, batched item changes
if (observableGroup != null)
{
NotifyCollectionChangedEventHandler onCollectionChanged = (o, e) => OnItemsSourceSingleCollectionChanged(o, e, insideLoop);
Disposable.Create(() => observableGroup.CollectionChanged -= onCollectionChanged)
.DisposeWith(disposables);
observableGroup.CollectionChanged += onCollectionChanged;
}
else
{
VectorChangedEventHandler<object> onVectorChanged = (o, e) => OnItemsSourceSingleCollectionChanged(o, e.ToNotifyCollectionChangedEventArgs(), insideLoop);
Disposable.Create(() =>
group.GroupItems.VectorChanged -= onVectorChanged
)
.DisposeWith(disposables);
group.GroupItems.VectorChanged += onVectorChanged;
}
if (group is INotifyPropertyChanged bindableGroup)
{
Disposable.Create(() =>
bindableGroup.PropertyChanged -= onPropertyChanged
)
.DisposeWith(disposables);
bindableGroup.PropertyChanged += onPropertyChanged;
void onPropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == "Group")
{
OnGroupPropertyChanged(group, insideLoop);
}
}
}
}
_notifyCollectionGroupsChanged.Disposable = disposables;
UpdateGroupCounts();
}
}
private void UpdateGroupCounts()
{
if (CollectionGroups != null)
{
var counts = new List<int>();
for (int i = 0; i < CollectionGroups.Count; i++)
{
var group = CollectionGroups[i] as ICollectionViewGroup;
counts.Add(group.GroupItems.Count);
}
_groupCounts = counts.ToArray();
}
else
{
_groupCounts = null;
}
}
/// <summary>
/// During an update, this will represent the group state immediately prior to the update.
/// </summary>
internal int GetCachedGroupCount(int groupIndex) => _groupCounts[groupIndex];
private void OnItemsSourceCollectionChanged(object sender, NotifyCollectionChangedEventArgs args)
{
OnItemsSourceSingleCollectionChanged(sender, args, section: 0);
}
private void OnItemsSourceGroupsVectorChanged(object sender, IVectorChangedEventArgs args) => OnItemsSourceGroupsChanged(sender, args.ToNotifyCollectionChangedEventArgs());
private void OnItemsSourceVectorChanged(object sender, IVectorChangedEventArgs args) => OnItemsSourceCollectionChanged(sender, args.ToNotifyCollectionChangedEventArgs());
/// <summary>
/// Called when a collection change occurs within a single group, or within the entire source if it is ungrouped.
/// </summary>
internal virtual void OnItemsSourceSingleCollectionChanged(object sender, NotifyCollectionChangedEventArgs args, int section)
{
UpdateItems();
}
/// <summary>
/// Called when a change is made to an observable collection of groups.
/// </summary>
internal virtual void OnItemsSourceGroupsChanged(object sender, NotifyCollectionChangedEventArgs args)
{
UpdateItems();
}
internal virtual void OnGroupPropertyChanged(ICollectionViewGroup group, int groupIndex)
{
}
partial void OnDisplayMemberPathChangedPartial(string oldDisplayMemberPath, string newDisplayMemberPath)
{
this.UpdateItemTemplateSelectorForDisplayMemberPath(newDisplayMemberPath);
}
protected override void OnApplyTemplate()
{
base.OnApplyTemplate();
_isReady = true;
UpdateItemsPanelRoot();
}
protected override void OnUnloaded()
{
base.OnUnloaded();
}
private void UpdateItemsPanelRoot()
{
// Remove items from the previous ItemsPanelRoot to ensure they can be safely added to the new one
if (ShouldItemsControlManageChildren)
{
ItemsPanelRoot?.Children.Clear();
}
var itemsPanel = ItemsPanel?.LoadContent() ?? new StackPanel();
InternalItemsPanelRoot = ResolveInternalItemsPanel(itemsPanel);
ItemsPanelRoot = itemsPanel as Panel;
ItemsPanelRoot?.SetItemsOwner(this);
_itemsPresenter?.SetItemsPanel(InternalItemsPanelRoot);
SetNeedsUpdateItems();
}
/// <summary>
/// Resolve the view to use as <see cref="InternalItemsPanelRoot"/>. Inheriting classes should
/// override this method if the 'real' displaying panel is different from the panel nominated by ItemsPanelTemplate.
/// </summary>
protected virtual View ResolveInternalItemsPanel(View itemsPanel)
{
return itemsPanel;
}
internal protected override void OnDataContextChanged(DependencyPropertyChangedEventArgs e)
{
base.OnDataContextChanged(e);
SyncDataContext();
}
protected virtual void SyncDataContext()
{
}
public void SetNeedsUpdateItems()
{
_needsUpdateItems = true;
RequestLayoutPartial();
}
public void UpdateItemsIfNeeded()
{
if (_needsUpdateItems)
{
_needsUpdateItems = false;
UpdateItems();
}
}
protected virtual void UpdateItems()
{
if (ItemsPanelRoot != null && ShouldItemsControlManageChildren)
{
_needsUpdateItems = false;
var items = GetItems() ?? Enumerable.Empty<object>();
var containers = items
.Cast<object>()
.Select((_, index) =>
{
var container = GetContainerForIndex(index);
PrepareContainerForIndex(container, index);
return container;
});
var results = ItemsPanelRoot.Children.UpdateWithResults(containers.OfType<View>(), comparer: new ViewComparer());
foreach (var removed in results.Removed)
{
if (removed is DependencyObject removedObject)
{
ClearContainerForItemOverride(removedObject, removedObject is ContentPresenter p ? p.Content : removedObject);
}
}
}
}
protected virtual void ClearContainerForItemOverride(global::Windows.UI.Xaml.DependencyObject element, object item)
{
if (element is ContentPresenter presenter
&& (
presenter.ContentTemplate == ItemTemplate
|| presenter.ContentTemplateSelector == ItemTemplateSelector
)
)
{
// Clear the Content property first, in order to avoid creating a text placeholder when
// the ContentTemplate is removed.
presenter.ClearValue(ContentPresenter.ContentProperty);
presenter.ClearValue(ContentPresenter.ContentTemplateProperty);
presenter.ClearValue(ContentPresenter.ContentTemplateSelectorProperty);
}
}
private class ViewComparer : IEqualityComparer<View>
{
public bool Equals(View x, View y)
{
return x.Equals(y);
}
public int GetHashCode(View obj)
{
return obj.GetHashCode();
}
}
/// <summary>
/// Creates or identifies the element that is used to display the given item.
/// </summary>
/// <returns>The element that is used to display the given item.</returns>
protected virtual DependencyObject GetContainerForItemOverride()
{
return InnerContentPresenterTemplate.LoadContentCached() as ContentPresenter;
}
/// <summary>
/// Prepares the specified element to display the specified item.
/// </summary>
/// <param name="element">The element that's used to display the specified item.</param>
/// <param name="item">The item to display.</param>
protected virtual void PrepareContainerForItemOverride(DependencyObject element, object item)
{
var isOwnContainer = element == item;
ContentControl containerAsContentControl;
ContentPresenter containerAsContentPresenter;
var styleFromItemsControl = ItemContainerStyle ?? ItemContainerStyleSelector?.SelectStyle(item, element);
//Prepare ContentPresenter
if ((containerAsContentPresenter = element as ContentPresenter) != null)
{
if (
containerAsContentPresenter.Style != null
&& containerAsContentPresenter.Style != styleFromItemsControl
)
{
// For now, styles-set properties are not reset when applying another style
// so we rely on the ClearStyle method to do this for this particular reuse
// case.
containerAsContentPresenter.Style.ClearStyle(containerAsContentPresenter);
}
if (styleFromItemsControl != null)
{
containerAsContentPresenter.Style = styleFromItemsControl;
}
else
{
containerAsContentPresenter.Style = null;
}
containerAsContentPresenter.ContentTemplate = ItemTemplate;
containerAsContentPresenter.ContentTemplateSelector = ItemTemplateSelector;
if (!isOwnContainer)
{
containerAsContentPresenter.Content = item;
}
}
//Prepare ContentControl
if ((containerAsContentControl = element as ContentControl) != null)
{
if (styleFromItemsControl != null)
{
containerAsContentControl.Style = styleFromItemsControl;
}
containerAsContentControl.ContentTemplate = ItemTemplate;
containerAsContentControl.ContentTemplateSelector = ItemTemplateSelector;
if (!isOwnContainer)
{
// Set the datacontext first, then the binding.
// This avoids the inner content to go through a partial content being
// the result of the fallback value of the binding set below.
containerAsContentControl.DataContext = item;
if (containerAsContentControl.GetBindingExpression(ContentControl.ContentProperty) == null)
{
containerAsContentControl.SetBinding(ContentControl.ContentProperty, new Binding());
}
}
}
}
/// <summary>
/// Determines whether the specified item is (or is eligible to be) its own container.
/// </summary>
/// <param name="item">The item to check.</param>
/// <returns>true if the item is (or is eligible to be) its own container; otherwise, false.</returns>
protected virtual bool IsItemItsOwnContainerOverride(object item)
{
return item is IFrameworkElement;
}
internal void PrepareContainerForIndex(DependencyObject container, int index)
{
_containerBeingPrepared = container;
// This must be set before calling PrepareContainerForItemOverride
container.SetValue(IndexForItemContainerProperty, index);