This repository was archived by the owner on Feb 25, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1.4k
Expand file tree
/
Copy pathDataGridRows.cs
More file actions
3610 lines (3184 loc) · 160 KB
/
DataGridRows.cs
File metadata and controls
3610 lines (3184 loc) · 160 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
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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using Microsoft.Toolkit.Uwp.UI.Automation.Peers;
using Microsoft.Toolkit.Uwp.UI.Controls.DataGridInternals;
using Microsoft.Toolkit.Uwp.UI.Utilities;
using Microsoft.Toolkit.Uwp.Utilities;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Media;
using DiagnosticsDebug = System.Diagnostics.Debug;
namespace Microsoft.Toolkit.Uwp.UI.Controls
{
/// <summary>
/// Control to represent data in columns and rows.
/// </summary>
public partial class DataGrid
{
internal bool AreRowBottomGridLinesRequired
{
get
{
return (this.GridLinesVisibility == DataGridGridLinesVisibility.Horizontal || this.GridLinesVisibility == DataGridGridLinesVisibility.All) && this.HorizontalGridLinesBrush != null;
}
}
internal int FirstVisibleSlot
{
get
{
return (this.SlotCount > 0) ? GetNextVisibleSlot(-1) : -1;
}
}
internal int FrozenColumnCountWithFiller
{
get
{
int count = this.FrozenColumnCount;
if (this.ColumnsInternal.RowGroupSpacerColumn.IsRepresented && (this.AreRowGroupHeadersFrozen || count > 0))
{
// Either the RowGroupHeaders are frozen by default or the user set a frozen column count. In both cases, we need to freeze
// one more column than the what the public value says
count++;
}
return count;
}
}
internal int LastVisibleSlot
{
get
{
return (this.SlotCount > 0) ? this.GetPreviousVisibleSlot(this.SlotCount) : -1;
}
}
// Cumulated height of all known rows, including the gridlines and details section.
// This property returns an approximation of the actual total row heights and also
// updates the RowHeightEstimate
private double EdgedRowsHeightCalculated
{
get
{
// If we're not displaying any rows or if we have infinite space the, relative height of our rows is 0
if (this.DisplayData.LastScrollingSlot == -1 || double.IsPositiveInfinity(this.AvailableSlotElementRoom))
{
if (_oldEdgedRowsHeightCalculated > 0)
{
_oldEdgedRowsHeightCalculated = 0;
LoadMoreDataFromIncrementalItemsSource(0);
}
return 0;
}
DiagnosticsDebug.Assert(this.DisplayData.LastScrollingSlot >= 0, "Expected positive DisplayData.LastScrollingSlot.");
DiagnosticsDebug.Assert(_verticalOffset >= 0, "Expected positive _verticalOffset.");
DiagnosticsDebug.Assert(this.NegVerticalOffset >= 0, "Expected positive NegVerticalOffset.");
// Height of all rows above the viewport
double totalRowsHeight = _verticalOffset - this.NegVerticalOffset;
// Add the height of all the rows currently displayed, AvailableRowRoom
// is not always up to date enough for this
foreach (UIElement element in this.DisplayData.GetScrollingElements())
{
DataGridRow row = element as DataGridRow;
if (row != null)
{
totalRowsHeight += row.TargetHeight;
}
else
{
totalRowsHeight += element.EnsureMeasured().DesiredSize.Height;
}
}
// Details up to and including viewport
int detailsCount = GetDetailsCountInclusive(0, this.DisplayData.LastScrollingSlot);
// Subtract details that were accounted for from the totalRowsHeight
totalRowsHeight -= detailsCount * this.RowDetailsHeightEstimate;
// Update the RowHeightEstimate if we have more row information
if (this.DisplayData.LastScrollingSlot >= _lastEstimatedRow)
{
_lastEstimatedRow = this.DisplayData.LastScrollingSlot;
this.RowHeightEstimate = totalRowsHeight / (_lastEstimatedRow + 1 - _collapsedSlotsTable.GetIndexCount(0, _lastEstimatedRow));
}
// Calculate estimates for what's beyond the viewport
if (this.VisibleSlotCount > this.DisplayData.NumDisplayedScrollingElements)
{
int remainingRowCount = this.SlotCount - this.DisplayData.LastScrollingSlot - _collapsedSlotsTable.GetIndexCount(this.DisplayData.LastScrollingSlot, this.SlotCount - 1) - 1;
// Add estimation for the cell heights of all rows beyond our viewport
totalRowsHeight += this.RowHeightEstimate * remainingRowCount;
// Add the rest of the details beyond the viewport
detailsCount += GetDetailsCountInclusive(this.DisplayData.LastScrollingSlot + 1, this.SlotCount - 1);
}
// TODO: Update the DetailsHeightEstimate
double totalDetailsHeight = detailsCount * this.RowDetailsHeightEstimate;
double newEdgedRowsHeightCalculated = totalRowsHeight + totalDetailsHeight;
bool loadMoreDataFromIncrementalItemsSource = newEdgedRowsHeightCalculated < _oldEdgedRowsHeightCalculated || (newEdgedRowsHeightCalculated == _oldEdgedRowsHeightCalculated && newEdgedRowsHeightCalculated < CellsHeight);
_oldEdgedRowsHeightCalculated = newEdgedRowsHeightCalculated;
if (loadMoreDataFromIncrementalItemsSource)
{
LoadMoreDataFromIncrementalItemsSource(newEdgedRowsHeightCalculated);
}
return newEdgedRowsHeightCalculated;
}
}
/// <summary>
/// Collapses the DataGridRowGroupHeader that represents a given CollectionViewGroup
/// </summary>
/// <param name="collectionViewGroup">CollectionViewGroup</param>
/// <param name="collapseAllSubgroups">Set to true to collapse all Subgroups</param>
public void CollapseRowGroup(ICollectionViewGroup collectionViewGroup, bool collapseAllSubgroups)
{
if (this.WaitForLostFocus(() => { this.CollapseRowGroup(collectionViewGroup, collapseAllSubgroups); }) ||
collectionViewGroup == null || !this.CommitEdit())
{
return;
}
EnsureRowGroupVisibility(RowGroupInfoFromCollectionViewGroup(collectionViewGroup), Visibility.Collapsed, true);
if (collapseAllSubgroups)
{
foreach (object groupObj in collectionViewGroup.GroupItems)
{
ICollectionViewGroup subGroup = groupObj as ICollectionViewGroup;
if (subGroup != null)
{
CollapseRowGroup(subGroup, collapseAllSubgroups);
}
}
}
}
/// <summary>
/// Expands the DataGridRowGroupHeader that represents a given CollectionViewGroup
/// </summary>
/// <param name="collectionViewGroup">CollectionViewGroup</param>
/// <param name="expandAllSubgroups">Set to true to expand all Subgroups</param>
public void ExpandRowGroup(ICollectionViewGroup collectionViewGroup, bool expandAllSubgroups)
{
if (this.WaitForLostFocus(() => { this.ExpandRowGroup(collectionViewGroup, expandAllSubgroups); }) ||
collectionViewGroup == null || !this.CommitEdit())
{
if (collectionViewGroup == null || !this.CommitEdit())
{
return;
}
}
EnsureRowGroupVisibility(RowGroupInfoFromCollectionViewGroup(collectionViewGroup), Visibility.Visible, true);
if (expandAllSubgroups)
{
foreach (object groupObj in collectionViewGroup.GroupItems)
{
ICollectionViewGroup subGroup = groupObj as ICollectionViewGroup;
if (subGroup != null)
{
ExpandRowGroup(subGroup, expandAllSubgroups);
}
}
}
}
/// <summary>
/// Raises the <see cref="E:System.Windows.Controls.DataGrid.RowDetailsVisibilityChanged" /> event.
/// </summary>
/// <param name="e">The event data.</param>
protected internal virtual void OnRowDetailsVisibilityChanged(DataGridRowDetailsEventArgs e)
{
this.RowDetailsVisibilityChanged?.Invoke(this, e);
}
/// <summary>
/// Clears the entire selection. Displayed rows are deselected explicitly to visualize
/// potential transition effects
/// </summary>
internal void ClearRowSelection(bool resetAnchorSlot)
{
if (resetAnchorSlot)
{
this.AnchorSlot = -1;
}
if (_selectedItems.Count > 0)
{
_noSelectionChangeCount++;
try
{
// Individually deselecting displayed rows to view potential transitions
for (int slot = this.DisplayData.FirstScrollingSlot;
slot > -1 && slot <= this.DisplayData.LastScrollingSlot;
slot++)
{
DataGridRow row = this.DisplayData.GetDisplayedElement(slot) as DataGridRow;
if (row != null)
{
if (_selectedItems.ContainsSlot(row.Slot))
{
SelectSlot(row.Slot, false);
}
}
}
_selectedItems.ClearRows();
this.SelectionHasChanged = true;
}
finally
{
this.NoSelectionChangeCount--;
}
}
}
/// <summary>
/// Clears the entire selection except the indicated row. Displayed rows are deselected explicitly to
/// visualize potential transition effects. The row indicated is selected if it is not already.
/// </summary>
internal void ClearRowSelection(int slotException, bool setAnchorSlot)
{
_noSelectionChangeCount++;
try
{
bool exceptionAlreadySelected = false;
if (_selectedItems.Count > 0)
{
// Individually deselecting displayed rows to view potential transitions
for (int slot = this.DisplayData.FirstScrollingSlot;
slot > -1 && slot <= this.DisplayData.LastScrollingSlot;
slot++)
{
if (slot != slotException && _selectedItems.ContainsSlot(slot))
{
SelectSlot(slot, false);
this.SelectionHasChanged = true;
}
}
exceptionAlreadySelected = _selectedItems.ContainsSlot(slotException);
int selectedCount = _selectedItems.Count;
if (selectedCount > 0)
{
if (selectedCount > 1)
{
this.SelectionHasChanged = true;
}
else
{
int currentlySelectedSlot = _selectedItems.GetIndexes().First();
if (currentlySelectedSlot != slotException)
{
this.SelectionHasChanged = true;
}
}
_selectedItems.ClearRows();
}
}
if (exceptionAlreadySelected)
{
// Exception row was already selected. It just needs to be marked as selected again.
// No transition involved.
_selectedItems.SelectSlot(slotException, true /*select*/);
if (setAnchorSlot)
{
this.AnchorSlot = slotException;
}
}
else
{
// Exception row was not selected. It needs to be selected with potential transition
SetRowSelection(slotException, true /*isSelected*/, setAnchorSlot);
}
}
finally
{
this.NoSelectionChangeCount--;
}
}
internal int GetCollapsedSlotCount(int startSlot, int endSlot)
{
return _collapsedSlotsTable.GetIndexCount(startSlot, endSlot);
}
internal int GetNextVisibleSlot(int slot)
{
return _collapsedSlotsTable.GetNextGap(slot);
}
internal int GetPreviousVisibleSlot(int slot)
{
return _collapsedSlotsTable.GetPreviousGap(slot);
}
internal Visibility GetRowDetailsVisibility(int rowIndex)
{
return GetRowDetailsVisibility(rowIndex, this.RowDetailsVisibilityMode);
}
internal Visibility GetRowDetailsVisibility(int rowIndex, DataGridRowDetailsVisibilityMode gridLevelRowDetailsVisibility)
{
DiagnosticsDebug.Assert(rowIndex != -1, "Expected rowIndex other than -1.");
if (_showDetailsTable.Contains(rowIndex))
{
// The user explicitly set DetailsVisibility on a row so we should respect that
return _showDetailsTable.GetValueAt(rowIndex);
}
else
{
if (gridLevelRowDetailsVisibility == DataGridRowDetailsVisibilityMode.Visible ||
(gridLevelRowDetailsVisibility == DataGridRowDetailsVisibilityMode.VisibleWhenSelected &&
_selectedItems.ContainsSlot(SlotFromRowIndex(rowIndex))))
{
return Visibility.Visible;
}
else
{
return Visibility.Collapsed;
}
}
}
/// <summary>
/// Returns the row associated to the provided backend data item.
/// </summary>
/// <param name="dataItem">backend data item</param>
/// <returns>null if the DataSource is null, the provided item in not in the source, or the item is not displayed; otherwise, the associated Row</returns>
internal DataGridRow GetRowFromItem(object dataItem)
{
int rowIndex = this.DataConnection.IndexOf(dataItem);
if (rowIndex < 0)
{
return null;
}
int slot = SlotFromRowIndex(rowIndex);
return IsSlotVisible(slot) ? this.DisplayData.GetDisplayedElement(slot) as DataGridRow : null;
}
internal bool GetRowSelection(int slot)
{
DiagnosticsDebug.Assert(slot != -1, "Expected slot other than -1.");
return _selectedItems.ContainsSlot(slot);
}
internal void InsertElementAt(
int slot,
int rowIndex,
object item,
DataGridRowGroupInfo groupInfo,
bool isCollapsed)
{
DiagnosticsDebug.Assert(slot >= 0, "Expected positive slot.");
DiagnosticsDebug.Assert(slot <= this.SlotCount, "Expected slot smaller than or equal to SlotCount.");
bool isRow = rowIndex != -1;
if (isCollapsed || (this.IsReadOnly && rowIndex == this.DataConnection.NewItemPlaceholderIndex))
{
InsertElement(slot, null /*element*/, true /*updateVerticalScrollBarOnly*/, true /*isCollapsed*/, isRow);
}
else if (SlotIsDisplayed(slot))
{
// Row at that index needs to be displayed
if (isRow)
{
InsertElement(slot, GenerateRow(rowIndex, slot, item), false /*updateVerticalScrollBarOnly*/, false /*isCollapsed*/, isRow);
}
else
{
InsertElement(slot, GenerateRowGroupHeader(slot, groupInfo), false /*updateVerticalScrollBarOnly*/, false /*isCollapsed*/, isRow);
}
}
else
{
InsertElement(slot, null, _vScrollBar == null || _vScrollBar.Visibility == Visibility.Visible /*updateVerticalScrollBarOnly*/, false /*isCollapsed*/, isRow);
}
}
internal void InsertRowAt(int rowIndex)
{
int slot = SlotFromRowIndex(rowIndex);
object item = this.DataConnection.GetDataItem(rowIndex);
// isCollapsed below is always false because we only use the method if we're not grouping
InsertElementAt(
slot,
rowIndex,
item,
null /*DataGridRowGroupInfo*/,
false /*isCollapsed*/);
}
internal bool IsColumnDisplayed(int columnIndex)
{
return columnIndex >= this.FirstDisplayedNonFillerColumnIndex && columnIndex <= this.DisplayData.LastTotallyDisplayedScrollingCol;
}
internal bool IsRowRecyclable(DataGridRow row)
{
return row != this.EditingRow && row != _focusedRow;
}
internal bool IsSlotVisible(int slot)
{
return slot >= this.DisplayData.FirstScrollingSlot &&
slot <= this.DisplayData.LastScrollingSlot &&
slot != -1 &&
!_collapsedSlotsTable.Contains(slot);
}
// detailsElement is the FrameworkElement created by the DetailsTemplate
internal void OnUnloadingRowDetails(DataGridRow row, FrameworkElement detailsElement)
{
OnUnloadingRowDetails(new DataGridRowDetailsEventArgs(row, detailsElement));
}
// detailsElement is the FrameworkElement created by the DetailsTemplate
internal void OnLoadingRowDetails(DataGridRow row, FrameworkElement detailsElement)
{
OnLoadingRowDetails(new DataGridRowDetailsEventArgs(row, detailsElement));
}
internal void OnRowDetailsVisibilityPropertyChanged(int rowIndex, Visibility visibility)
{
DiagnosticsDebug.Assert(rowIndex >= 0, "Expected positive rowIndex.");
DiagnosticsDebug.Assert(rowIndex < this.SlotCount, "Expected rowIndex smaller than SlotCount.");
_showDetailsTable.AddValue(rowIndex, visibility);
}
internal void OnRowGroupHeaderToggled(DataGridRowGroupHeader groupHeader, Visibility newVisibility, bool setCurrent)
{
DiagnosticsDebug.Assert(groupHeader.RowGroupInfo.CollectionViewGroup.GroupItems.Count > 0, "Expected positive groupHeader.RowGroupInfo.CollectionViewGroup.GroupItems.Count.");
if (this.WaitForLostFocus(() => { this.OnRowGroupHeaderToggled(groupHeader, newVisibility, setCurrent); }) || !this.CommitEdit())
{
return;
}
if (setCurrent && this.CurrentSlot != groupHeader.RowGroupInfo.Slot)
{
// Most of the time this is set by the MouseLeftButtonDown handler but validation could cause that code path to fail
UpdateSelectionAndCurrency(this.CurrentColumnIndex, groupHeader.RowGroupInfo.Slot, DataGridSelectionAction.SelectCurrent, false /*scrollIntoView*/);
}
UpdateRowGroupVisibility(groupHeader.RowGroupInfo, newVisibility, true /*isHeaderDisplayed*/);
ComputeScrollBarsLayout();
// We need force arrange since our Scrollings Rows could update without automatically triggering layout
InvalidateRowsArrange();
}
internal void OnRowsMeasure()
{
if (!DoubleUtil.IsZero(this.DisplayData.PendingVerticalScrollHeight))
{
ScrollSlotsByHeight(this.DisplayData.PendingVerticalScrollHeight);
this.DisplayData.PendingVerticalScrollHeight = 0;
}
}
internal void OnSublevelIndentUpdated(DataGridRowGroupHeader groupHeader, double newValue)
{
DiagnosticsDebug.Assert(this.DataConnection.CollectionView != null, "Expected non-null DataConnection.CollectionView.");
DiagnosticsDebug.Assert(this.DataConnection.CollectionView.CollectionGroups != null, "Expected non-null DataConnection.CollectionView.CollectionGroups.");
DiagnosticsDebug.Assert(this.RowGroupSublevelIndents != null, "Expected non-null RowGroupSublevelIndents.");
#if FEATURE_ICOLLECTIONVIEW_GROUP
int groupLevelCount = this.DataConnection.CollectionView.GroupDescriptions.Count;
#else
int groupLevelCount = 1;
#endif
DiagnosticsDebug.Assert(groupHeader.Level >= 0, "Expected positive groupHeader.Level.");
DiagnosticsDebug.Assert(groupHeader.Level < groupLevelCount, "Expected groupHeader.Level smaller than groupLevelCount.");
double oldValue = this.RowGroupSublevelIndents[groupHeader.Level];
if (groupHeader.Level > 0)
{
oldValue -= this.RowGroupSublevelIndents[groupHeader.Level - 1];
}
// Update the affected values in our table by the amount affected
double change = newValue - oldValue;
for (int i = groupHeader.Level; i < groupLevelCount; i++)
{
this.RowGroupSublevelIndents[i] += change;
DiagnosticsDebug.Assert(this.RowGroupSublevelIndents[i] >= 0, "Expected positive RowGroupSublevelIndents[i].");
}
EnsureRowGroupSpacerColumnWidth(groupLevelCount);
}
internal void RefreshRows(bool recycleRows, bool clearRows)
{
if (_measured)
{
// _desiredCurrentColumnIndex is used in MakeFirstDisplayedCellCurrentCell to set the
// column position back to what it was before the refresh
_desiredCurrentColumnIndex = this.CurrentColumnIndex;
double verticalOffset = _verticalOffset;
if (this.DisplayData.PendingVerticalScrollHeight > 0)
{
// Use the pending vertical scrollbar position if there is one, in the case that the collection
// has been reset multiple times in a row.
verticalOffset = this.DisplayData.PendingVerticalScrollHeight;
}
VerticalOffset = 0;
this.NegVerticalOffset = 0;
if (clearRows)
{
ClearRows(recycleRows);
ClearRowGroupHeadersTable();
PopulateRowGroupHeadersTable();
RefreshSlotCounts();
}
RefreshRowGroupHeaders();
// Update the CurrentSlot because it might have changed
if (recycleRows && this.DataConnection.CollectionView != null)
{
this.CurrentSlot = this.DataConnection.CollectionView.CurrentPosition == -1
? -1 : SlotFromRowIndex(this.DataConnection.CollectionView.CurrentPosition);
if (this.CurrentSlot == -1)
{
SetCurrentCellCore(-1, -1);
}
}
if (this.DataConnection != null && this.ColumnsItemsInternal.Count > 0)
{
int slotCount = this.DataConnection.Count;
slotCount += this.RowGroupHeadersTable.IndexCount;
AddSlots(slotCount);
InvalidateMeasure();
}
EnsureRowGroupSpacerColumn();
if (this.VerticalScrollBar != null)
{
this.DisplayData.PendingVerticalScrollHeight = Math.Min(verticalOffset, this.VerticalScrollBar.Maximum);
}
}
else
{
if (clearRows)
{
ClearRows(recycleRows /*recycle*/);
}
ClearRowGroupHeadersTable();
PopulateRowGroupHeadersTable();
RefreshSlotCounts();
}
}
internal void RemoveRowAt(int rowIndex, object item)
{
RemoveElementAt(SlotFromRowIndex(rowIndex), item, true);
}
internal DataGridRowGroupInfo RowGroupInfoFromCollectionViewGroup(ICollectionViewGroup collectionViewGroup)
{
foreach (int slot in this.RowGroupHeadersTable.GetIndexes())
{
DataGridRowGroupInfo rowGroupInfo = this.RowGroupHeadersTable.GetValueAt(slot);
if (rowGroupInfo.CollectionViewGroup == collectionViewGroup)
{
return rowGroupInfo;
}
}
return null;
}
internal int RowIndexFromSlot(int slot)
{
return slot - this.RowGroupHeadersTable.GetIndexCount(0, slot);
}
internal bool ScrollSlotIntoView(int slot, bool scrolledHorizontally)
{
DiagnosticsDebug.Assert(_collapsedSlotsTable.Contains(slot) || !IsSlotOutOfBounds(slot), "Expected _collapsedSlotsTable.Contains(slot) is true or IsSlotOutOfBounds(slot) is false.");
if (scrolledHorizontally && this.DisplayData.FirstScrollingSlot <= slot && this.DisplayData.LastScrollingSlot >= slot)
{
// If the slot is displayed and we scrolled horizontally, column virtualization could cause the rows to grow.
// As a result we need to force measure on the rows we're displaying and recalculate our First and Last slots
// so they're accurate
foreach (DataGridRow row in this.DisplayData.GetScrollingElements(true /*onlyRows*/))
{
row.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
}
UpdateDisplayedRows(this.DisplayData.FirstScrollingSlot, this.CellsHeight);
}
if (this.DisplayData.FirstScrollingSlot < slot && this.DisplayData.LastScrollingSlot > slot)
{
// The row is already displayed in its entirety
return true;
}
else if (this.DisplayData.FirstScrollingSlot == slot && slot != -1)
{
if (!DoubleUtil.IsZero(this.NegVerticalOffset))
{
// First displayed row is partially scrolled of. Let's scroll it so that this.NegVerticalOffset becomes 0.
this.DisplayData.PendingVerticalScrollHeight = -this.NegVerticalOffset;
InvalidateRowsMeasure(false /*invalidateIndividualRows*/);
}
return true;
}
double deltaY = 0;
int firstFullSlot;
if (this.DisplayData.FirstScrollingSlot > slot)
{
// Scroll up to the new row so it becomes the first displayed row
firstFullSlot = this.DisplayData.FirstScrollingSlot - 1;
if (DoubleUtil.GreaterThan(this.NegVerticalOffset, 0))
{
deltaY = -this.NegVerticalOffset;
}
deltaY -= GetSlotElementsHeight(slot, firstFullSlot);
if (this.DisplayData.FirstScrollingSlot - slot > 1)
{
// TODO: This will likely discard and create a small number of the same rows so we could probably
// optimize this. The optimization would only affect the PageUp key.
ResetDisplayedRows();
}
this.NegVerticalOffset = 0;
UpdateDisplayedRows(slot, this.CellsHeight);
}
else if (this.DisplayData.LastScrollingSlot <= slot)
{
// Scroll down to the new row so it's entirely displayed. If the height of the row
// is greater than the height of the DataGrid, then show the top of the row at the top
// of the grid.
firstFullSlot = this.DisplayData.LastScrollingSlot;
// Figure out how much of the last row is cut off.
double rowHeight = GetExactSlotElementHeight(this.DisplayData.LastScrollingSlot);
double availableHeight = this.AvailableSlotElementRoom + rowHeight;
if (DoubleUtil.AreClose(rowHeight, availableHeight))
{
if (this.DisplayData.LastScrollingSlot == slot)
{
// We're already at the very bottom so we don't need to scroll down further.
return true;
}
else
{
// We're already showing the entire last row so don't count it as part of the delta.
firstFullSlot++;
}
}
else if (rowHeight > availableHeight)
{
firstFullSlot++;
deltaY += rowHeight - availableHeight;
}
// sum up the height of the rest of the full rows.
if (slot >= firstFullSlot)
{
deltaY += GetSlotElementsHeight(firstFullSlot, slot);
}
// If the first row we're displaying is no longer adjacent to the rows we have
// simply discard the ones we have.
if (slot - this.DisplayData.LastScrollingSlot > 1)
{
ResetDisplayedRows();
}
if (DoubleUtil.GreaterThanOrClose(GetExactSlotElementHeight(slot), this.CellsHeight))
{
// The entire row won't fit in the DataGrid so we start showing it from the top.
this.NegVerticalOffset = 0;
UpdateDisplayedRows(slot, this.CellsHeight);
}
else
{
UpdateDisplayedRowsFromBottom(slot);
}
}
VerticalOffset += deltaY;
if (_verticalOffset < 0 || this.DisplayData.FirstScrollingSlot == 0)
{
// We scrolled too far because a row's height was larger than its approximation.
VerticalOffset = this.NegVerticalOffset;
}
// TODO: in certain cases (eg, variable row height), this may not be true
DiagnosticsDebug.Assert(DoubleUtil.LessThanOrClose(this.NegVerticalOffset, _verticalOffset), "Expected NegVerticalOffset is less than or close to _verticalOffset.");
SetVerticalOffset(_verticalOffset);
InvalidateMeasure();
InvalidateRowsMeasure(false /*invalidateIndividualRows*/);
return true;
}
internal void SetRowSelection(int slot, bool isSelected, bool setAnchorSlot)
{
DiagnosticsDebug.Assert(isSelected || !setAnchorSlot, "Expected isSelected is true or setAnchorSlot is false.");
DiagnosticsDebug.Assert(!IsSlotOutOfSelectionBounds(slot), "Expected IsSlotOutOfSelectionBounds(slot) is false.");
_noSelectionChangeCount++;
try
{
if (this.SelectionMode == DataGridSelectionMode.Single && isSelected)
{
DiagnosticsDebug.Assert(_selectedItems.Count <= 1, "Expected _selectedItems.Count smaller than or equal to 1.");
if (_selectedItems.Count > 0)
{
int currentlySelectedSlot = _selectedItems.GetIndexes().First();
if (currentlySelectedSlot != slot)
{
SelectSlot(currentlySelectedSlot, false);
this.SelectionHasChanged = true;
}
}
}
if (_selectedItems.ContainsSlot(slot) != isSelected)
{
SelectSlot(slot, isSelected);
this.SelectionHasChanged = true;
}
if (setAnchorSlot)
{
this.AnchorSlot = slot;
}
}
finally
{
this.NoSelectionChangeCount--;
}
}
// For now, all scenarios are for isSelected == true.
internal void SetRowsSelection(int startSlot, int endSlot, bool isSelected = true)
{
DiagnosticsDebug.Assert(startSlot >= 0, "Expected startSlot is positive.");
DiagnosticsDebug.Assert(startSlot < this.SlotCount, "Expected startSlot is smaller than SlotCount.");
DiagnosticsDebug.Assert(endSlot >= 0, "Expected endSlot is positive.");
DiagnosticsDebug.Assert(endSlot < this.SlotCount, "Expected endSlot is smaller than SlotCount.");
DiagnosticsDebug.Assert(startSlot <= endSlot, "Expected startSlot is smaller than or equal to endSlot.");
_noSelectionChangeCount++;
try
{
if (isSelected && !_selectedItems.ContainsAll(startSlot, endSlot))
{
// At least one row gets selected
SelectSlots(startSlot, endSlot, true);
this.SelectionHasChanged = true;
}
}
finally
{
this.NoSelectionChangeCount--;
}
}
internal int SlotFromRowIndex(int rowIndex)
{
return rowIndex + this.RowGroupHeadersTable.GetIndexCountBeforeGap(0, rowIndex);
}
private static void CorrectRowAfterDeletion(DataGridRow row, bool rowDeleted)
{
row.Slot--;
if (rowDeleted)
{
row.Index--;
}
}
private static void CorrectRowAfterInsertion(DataGridRow row, bool rowInserted)
{
row.Slot++;
if (rowInserted)
{
row.Index++;
}
}
private void AddSlotElement(int slot, UIElement element)
{
#if DEBUG
DataGridRow row = element as DataGridRow;
if (row != null)
{
DiagnosticsDebug.Assert(row.OwningGrid == this, "Expected row.OwningGrid equals this DataGrid.");
DiagnosticsDebug.Assert(row.Cells.Count == this.ColumnsItemsInternal.Count, "Expected row.Cells.Count equals this.ColumnsItemsInternal.Count.");
int columnIndex = 0;
foreach (DataGridCell dataGridCell in row.Cells)
{
DiagnosticsDebug.Assert(dataGridCell.OwningRow == row, "Expected dataGridCell.OwningRow equals row.");
DiagnosticsDebug.Assert(dataGridCell.OwningColumn == this.ColumnsItemsInternal[columnIndex], "Expected dataGridCell.OwningColumn equals this.ColumnsItemsInternal[columnIndex].");
columnIndex++;
}
}
#endif
DiagnosticsDebug.Assert(slot == this.SlotCount, "Expected slot equals this.SlotCount.");
OnAddedElement_Phase1(slot, element);
this.SlotCount++;
this.VisibleSlotCount++;
OnAddedElement_Phase2(slot, false /*updateVerticalScrollBarOnly*/);
OnElementsChanged(true /*grew*/);
}
private void AddSlots(int totalSlots)
{
this.SlotCount = 0;
this.VisibleSlotCount = 0;
IEnumerator<int> groupSlots = null;
int nextGroupSlot = -1;
if (this.RowGroupHeadersTable.RangeCount > 0)
{
groupSlots = this.RowGroupHeadersTable.GetIndexes().GetEnumerator();
if (groupSlots != null && groupSlots.MoveNext())
{
nextGroupSlot = groupSlots.Current;
}
}
int slot = 0;
int addedRows = 0;
while (slot < totalSlots && this.AvailableSlotElementRoom > 0)
{
if (slot == nextGroupSlot)
{
DataGridRowGroupInfo groupRowInfo = this.RowGroupHeadersTable.GetValueAt(slot);
AddSlotElement(slot, GenerateRowGroupHeader(slot, groupRowInfo));
nextGroupSlot = groupSlots.MoveNext() ? groupSlots.Current : -1;
}
else
{
AddSlotElement(slot, GenerateRow(addedRows, slot));
addedRows++;
}
slot++;
}
if (slot < totalSlots)
{
this.SlotCount += totalSlots - slot;
this.VisibleSlotCount += totalSlots - slot;
OnAddedElement_Phase2(0, _vScrollBar == null || _vScrollBar.Visibility == Visibility.Visible /*updateVerticalScrollBarOnly*/);
OnElementsChanged(true /*grew*/);
}
}
private void ApplyDisplayedRowsState(int startSlot, int endSlot)
{
int firstSlot = Math.Max(this.DisplayData.FirstScrollingSlot, startSlot);
int lastSlot = Math.Min(this.DisplayData.LastScrollingSlot, endSlot);
if (firstSlot >= 0)
{
DiagnosticsDebug.Assert(lastSlot >= firstSlot, "lastSlot greater than or equal to firstSlot.");
int slot = GetNextVisibleSlot(firstSlot - 1);
while (slot <= lastSlot)
{
DataGridRow row = this.DisplayData.GetDisplayedElement(slot) as DataGridRow;
if (row != null)
{
row.ApplyState(true /*animate*/);
}
slot = GetNextVisibleSlot(slot);
}
}
}
private void ClearRowGroupHeadersTable()
{
// Detach existing handlers on CollectionViewGroup.Items.CollectionChanged
foreach (int slot in this.RowGroupHeadersTable.GetIndexes())
{
DataGridRowGroupInfo groupInfo = this.RowGroupHeadersTable.GetValueAt(slot);
if (groupInfo.CollectionViewGroup.GroupItems != null)
{
#if FEATURE_ICOLLECTIONVIEW_GROUP
UnhookCollectionChangedListenerFromGroup(groupInfo.CollectionViewGroup.GroupItems as INotifyCollectionChanged, false /*removeFromTable*/);
#else
UnhookVectorChangedListenerFromGroup(groupInfo.CollectionViewGroup.GroupItems, false /*removeFromTable*/);
#endif
}
#if FEATURE_ICOLLECTIONVIEW_GROUP
WeakEventListener<DataGrid, object, PropertyChangedEventArgs> weakPropertyChangedListener;
INotifyPropertyChanged inpc = groupInfo.CollectionViewGroup as INotifyPropertyChanged;
if (inpc != null && _groupsPropertyChangedListenersTable.TryGetValue(inpc, out weakPropertyChangedListener))
{
weakPropertyChangedListener.Detach();
}
#endif
}
if (_topLevelGroup != null)
{
#if FEATURE_ICOLLECTIONVIEW_GROUP
UnhookCollectionChangedListenerFromGroup(_topLevelGroup as INotifyCollectionChanged, false /*removeFromTable*/);
#else
UnhookVectorChangedListenerFromGroup(_topLevelGroup, false /*removeFromTable*/);
#endif
_topLevelGroup = null;
}
#if FEATURE_ICOLLECTIONVIEW_GROUP
_groupsPropertyChangedListenersTable.Clear();
_groupsCollectionChangedListenersTable.Clear();
#endif
this.RowGroupHeadersTable.Clear();
_collapsedSlotsTable.Clear();
_rowGroupHeightsByLevel = null;
RowGroupSublevelIndents = null;
}
private void ClearRows(bool recycle)
{
// Need to clean up recycled rows even if the RowCount is 0
SetCurrentCellCore(-1, -1, false /*commitEdit*/, false /*endRowEdit*/);
ClearRowSelection(true /*resetAnchorSlot*/);
UnloadElements(recycle);
this.ClearShowDetailsTable();
this.SlotCount = 0;
this.NegVerticalOffset = 0;
SetVerticalOffset(0);
ComputeScrollBarsLayout();
}
private void ClearShowDetailsTable()
{