-
Notifications
You must be signed in to change notification settings - Fork 61
Expand file tree
/
Copy pathTableView.cs
More file actions
2817 lines (2418 loc) · 96.7 KB
/
Copy pathTableView.cs
File metadata and controls
2817 lines (2418 loc) · 96.7 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
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Controls;
using Microsoft.UI.Xaml.Controls.Primitives;
using Microsoft.UI.Xaml.Data;
using Microsoft.UI.Xaml.Input;
using Microsoft.UI.Xaml.Media;
using System.Collections;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Reflection;
using System.Text;
using Windows.ApplicationModel.DataTransfer;
using Windows.Foundation;
using Windows.Storage;
using Windows.Storage.Pickers;
using Windows.System;
using WinUI.TableView.Extensions;
using WinUI.TableView.Helpers;
using Pointer = Microsoft.UI.Xaml.Input.Pointer;
namespace WinUI.TableView;
/// <summary>
/// Represents a control that displays data in customizable table-like interface.
/// </summary>
[StyleTypedProperty(Property = nameof(ColumnHeaderStyle), StyleTargetType = typeof(TableViewColumnHeader))]
[StyleTypedProperty(Property = nameof(CellStyle), StyleTargetType = typeof(TableViewCell))]
public partial class TableView : ListView
{
private TableViewHeaderRow? _headerRow;
private ScrollViewer? _scrollViewer;
private RowDefinition? _headerRowDefinition;
private bool _shouldThrowSelectionModeChangedException;
private bool _ensureColumns = true;
private bool _isItemsSourceSuspended;
private readonly List<TableViewRow> _rows = [];
private readonly CollectionView _collectionView = [];
private Border? _dragRectangle;
private Point? _dragStartPoint;
private bool _suppressSelectionChangedCellClear;
private Point? _lastDragCanvasPoint;
private DispatcherTimer? _autoScrollTimer;
private double _autoScrollVerticalDelta;
private double _autoScrollHorizontalDelta;
private double _dragStartVerticalOffset;
private double _dragStartHorizontalOffset;
private Pointer? _tableViewDragPointer;
private UIElement? _pointerCaptureElement;
private TableViewCellSlotRange? _lastDragSelectionCellRange;
private ItemIndexRange? _lastDragSelectionRowRange;
private bool _cellStateDispatchPending;
private readonly HashSet<int> _pendingCellStateRows = [];
private TableViewColumn? _resizingColumn;
private double _resizingOriginalWidth;
private readonly List<TableViewCell> _resizingPreviewCells = [];
private readonly List<TableViewCell> _resizingDownstreamCells = [];
private readonly List<(Panel Panel, TranslateTransform Shift)> _resizingScrollableShifts = [];
/// <summary>
/// Initializes a new instance of the TableView class.
/// </summary>
public TableView()
{
DefaultStyleKey = typeof(TableView);
Columns = new TableViewColumnsCollection(this);
FilterHandler = new ColumnFilterHandler(this);
base.ItemsSource = _collectionView;
base.SelectionMode = SelectionMode;
SetValue(ConditionalCellStylesProperty, new TableViewConditionalCellStylesCollection());
RegisterPropertyChangedCallback(ItemsControl.ItemsSourceProperty, OnBaseItemsSourceChanged);
RegisterPropertyChangedCallback(ListViewBase.SelectionModeProperty, OnBaseSelectionModeChanged);
Loaded += OnLoaded;
Unloaded += OnUnloaded;
SelectionChanged += TableView_SelectionChanged;
_collectionView.ItemPropertyChanged += OnItemPropertyChanged;
AddHandler(PointerPressedEvent, new PointerEventHandler(OnAnyPointerPressed), handledEventsToo: true);
AddHandler(PointerReleasedEvent, new PointerEventHandler(OnAnyPointerReleased), handledEventsToo: true);
}
/// <summary>
/// Handles the SelectionChanged event of the TableView control.
/// </summary>
private void TableView_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
TableViewTrace.Write($"TableViewSelectionChanged: AddedItems={e.AddedItems.Count}, RemovedItems={e.RemovedItems.Count}");
if (_suppressSelectionChangedCellClear)
{
_suppressSelectionChangedCellClear = false;
}
else
{
if (!KeyboardHelper.IsCtrlKeyDown())
{
SelectedCellRanges.Clear();
}
else
{
var addedIndexes = e.AddedItems
.Select(item => Items.IndexOf(item))
.Where(i => i >= 0);
if (Columns.VisibleColumns.Count == 0) return;
foreach (var range in IndexRangeHelper.GetRanges(addedIndexes))
{
var slotRange = TableViewCellSlotRange.FromCoordinates(range.FirstIndex, 0, range.LastIndex, Columns.VisibleColumns.Count - 1);
SubtractCellRangeFromSelection(slotRange);
}
}
CurrentCellSlot = null;
OnCellSelectionChanged();
}
if (SelectedItems?.Count == 1)
{
DispatcherQueue.TryEnqueue(async () => await ScrollRowIntoView(SelectedIndex));
}
}
/// <summary>
/// Subtracts a specified cell range from the current selection.
/// </summary>
/// <param name="slotRange">The cell range to subtract from the current selection.</param>
private void SubtractCellRangeFromSelection(TableViewCellSlotRange slotRange)
{
while (SelectedCellRanges.FirstOrDefault(r => r.IntersectsWith(slotRange)) is { } intersectingRange)
{
foreach (var slicedRange in intersectingRange.Subtract(slotRange))
{
SelectedCellRanges.Add(slicedRange);
}
SelectedCellRanges.Remove(intersectingRange);
}
}
/// <summary>
/// Handles the PropertyChanged event of an item in the TableView.
/// </summary>
private void OnItemPropertyChanged(object? sender, PropertyChangedEventArgs e)
{
var row = ContainerFromItem(sender) as TableViewRow;
row?.EnsureCellsStyle(default, sender);
}
/// <inheritdoc/>
protected override void PrepareContainerForItemOverride(DependencyObject element, object item)
{
base.PrepareContainerForItemOverride(element, item);
DispatcherQueue.TryEnqueue(() =>
{
if (element is TableViewRow row)
{
if (!_rows.Contains(row))
{
_rows.Add(row);
}
row.TableView = this;
row.EnsureCellsStyle(default, item);
_pendingCellStateRows.Add(row.Index);
if (!_cellStateDispatchPending)
{
_cellStateDispatchPending = true;
DispatcherQueue.TryEnqueue(ApplyPendingCellStates);
}
row.RowPresenter?.ApplyDetailsPaneState(item);
if (CurrentCellSlot.HasValue)
{
row.ApplyCurrentCellState(CurrentCellSlot.Value);
}
}
});
}
/// <inheritdoc/>
protected override void ClearContainerForItemOverride(DependencyObject element, object item)
{
if (element is TableViewRow row)
{
_rows.Remove(row);
row.TableView = null;
}
base.ClearContainerForItemOverride(element, item);
}
/// <inheritdoc/>
protected override DependencyObject GetContainerForItemOverride()
{
var row = new TableViewRow { TableView = this };
// Set bindings for FontFamily and FontSize to propagate from TableView to TableViewRow
row.SetBinding(FontFamilyProperty, new Binding { Path = new("TableView.FontFamily"), RelativeSource = new() { Mode = RelativeSourceMode.Self } });
row.SetBinding(FontSizeProperty, new Binding { Path = new("TableView.FontSize"), RelativeSource = new() { Mode = RelativeSourceMode.Self } });
_rows.Add(row);
return row;
}
/// <summary>
/// Gets a value indicating whether a column is currently being resized by the user via a live
/// drag preview (see <see cref="BeginColumnResizePreview"/>).
/// </summary>
internal bool IsColumnResizing { get; private set; }
/// <summary>
/// Starts a live resize-drag preview for <paramref name="column"/>: generously (re)measures the
/// column's currently-realized cells once, and creates the per-cell composition-only clip/shift
/// state that <see cref="UpdateColumnResizePreview"/> will mutate on every subsequent pointer-move
/// frame. No real layout (Width/ActualWidth) is touched here or during the drag — that only
/// happens once, in <see cref="EndColumnResizePreview"/>.
/// </summary>
internal void BeginColumnResizePreview(TableViewColumn column)
{
var visibleColumns = Columns.VisibleColumns;
var columnIndex = visibleColumns.IndexOf(column);
if (columnIndex < 0)
{
return;
}
_resizingColumn = column;
_resizingOriginalWidth = column.ActualWidth;
IsColumnResizing = true;
column.IsResizing = true;
var effectiveMax = column.MaxWidth ?? MaxColumnWidth;
if (double.IsPositiveInfinity(effectiveMax))
{
effectiveMax = 4000d;
}
_resizingPreviewCells.Clear();
_resizingDownstreamCells.Clear();
_resizingScrollableShifts.Clear();
foreach (var row in _rows)
{
foreach (var cell in row.Cells)
{
if (cell.Column is null || cell.Column.IsFrozen != column.IsFrozen)
{
continue;
}
if (cell.Column == column)
{
cell.BeginResizePreview(effectiveMax);
_resizingPreviewCells.Add(cell);
}
else if (visibleColumns.IndexOf(cell.Column) > columnIndex)
{
cell.ApplyDownstreamShift();
_resizingDownstreamCells.Add(cell);
}
}
if (column.IsFrozen && row.RowPresenter?.ScrollableCellsPanel is { } scrollablePanel)
{
var shift = new TranslateTransform();
scrollablePanel.RenderTransform = shift;
_resizingScrollableShifts.Add((scrollablePanel, shift));
}
}
}
/// <summary>
/// Updates the live resize-drag preview to <paramref name="liveWidth"/>. The only work done per
/// pointer-move frame: mutate each touched cell's own (not shared — see
/// <see cref="TableViewCell.BeginResizePreview"/>) clip/shift in place. No Measure/Arrange, just
/// cheap composition-only property writes, still nowhere near the cost of the real layout cascade
/// this preview mechanism replaces.
/// </summary>
internal void UpdateColumnResizePreview(double liveWidth)
{
if (_resizingColumn is null)
{
return;
}
var delta = liveWidth - _resizingOriginalWidth;
foreach (var cell in _resizingPreviewCells)
{
cell.UpdateResizePreviewClip(liveWidth, cell.ActualHeight);
cell.UpdateGridLineShift(delta);
}
foreach (var cell in _resizingDownstreamCells)
{
cell.UpdateDownstreamShift(delta);
}
foreach (var (_, shift) in _resizingScrollableShifts)
{
shift.X = delta;
}
}
/// <summary>
/// Ends the live resize-drag preview, synchronously: clears every clip/transform the preview
/// touched, then — if <paramref name="commitWidth"/> is not null — performs the single real width
/// commit (<see cref="TableViewColumn.ActualWidth"/> then <see cref="TableViewColumn.Width"/>),
/// cascading into a normal, one-time layout pass. Doing this all in one synchronous call (no
/// await/DispatcherQueue in between) means the compositor never presents an intermediate frame —
/// the preview's last shown state and the committed real state are numerically identical.
/// </summary>
internal void EndColumnResizePreview(double? commitWidth)
{
if (_resizingColumn is null)
{
return;
}
var column = _resizingColumn;
_resizingColumn = null;
IsColumnResizing = false;
column.IsResizing = false;
foreach (var cell in _resizingPreviewCells)
{
cell.EndResizePreview();
}
foreach (var cell in _resizingDownstreamCells)
{
cell.EndResizePreview();
}
foreach (var (panel, _) in _resizingScrollableShifts)
{
panel.RenderTransform = null;
}
_resizingPreviewCells.Clear();
_resizingDownstreamCells.Clear();
_resizingScrollableShifts.Clear();
if (commitWidth is double width)
{
column.ActualWidth = width;
column.Width = new GridLength(width, GridUnitType.Pixel);
}
}
/// <summary>
/// Starts a <see cref="TableViewColumnResizeMode.Live"/> resize drag for <paramref name="column"/>:
/// unlike <see cref="BeginColumnResizePreview"/>, no cell state is touched here — every frame's
/// width change goes through the normal, real <see cref="TableViewColumn.ActualWidth"/> cascade
/// instead (see <see cref="UpdateColumnResizeLive"/>).
/// </summary>
internal void BeginColumnResizeLive(TableViewColumn column)
{
_resizingColumn = column;
IsColumnResizing = true;
column.IsResizing = true;
}
/// <summary>
/// Updates a <see cref="TableViewColumnResizeMode.Live"/> resize drag to <paramref name="liveWidth"/>
/// by setting <see cref="TableViewColumn.ActualWidth"/> directly — every visible row's cell
/// relayouts for real on every call. Deliberately does not touch <see cref="TableViewColumn.Width"/>
/// (which would additionally re-run <c>CalculateHeaderWidths</c> for every column on every frame);
/// that commit happens once, in <see cref="EndColumnResizeLive"/>.
/// </summary>
internal void UpdateColumnResizeLive(double liveWidth)
{
if (_resizingColumn is null)
{
return;
}
_resizingColumn.ActualWidth = liveWidth;
}
/// <summary>
/// Ends a <see cref="TableViewColumnResizeMode.Live"/> resize drag. <see cref="TableViewColumn.ActualWidth"/>
/// already reflects the live width from <see cref="UpdateColumnResizeLive"/>, so only the
/// <see cref="TableViewColumn.Width"/> GridLength commit is left to do here.
/// </summary>
internal void EndColumnResizeLive(double? commitWidth)
{
if (_resizingColumn is null)
{
return;
}
var column = _resizingColumn;
_resizingColumn = null;
IsColumnResizing = false;
column.IsResizing = false;
if (commitWidth is double width)
{
column.Width = new GridLength(width, GridUnitType.Pixel);
}
}
/// <inheritdoc/>
protected override void OnKeyDown(KeyRoutedEventArgs e)
{
var shiftKey = KeyboardHelper.IsShiftKeyDown();
var ctrlKey = KeyboardHelper.IsCtrlKeyDown();
if (HandleShortKeys(shiftKey, ctrlKey, e.Key))
{
e.Handled = true;
return;
}
HandleNavigations(e, shiftKey, ctrlKey);
}
/// <summary>
/// Handles pointer-pressed for all cases, including when elements sets <c>e.Handled = true</c>.
/// </summary>
private void OnAnyPointerPressed(object sender, PointerRoutedEventArgs e)
{
var pointerPoint = e.GetCurrentPoint(this);
var position = pointerPoint.Position;
var canvasPoint = GetCanvasPoint(position);
var ctrlKey = KeyboardHelper.IsCtrlKeyDown();
var isShiftKey = KeyboardHelper.IsShiftKeyDown();
var orignalSoruce = e.OriginalSource as FrameworkElement;
UIElement? pressedElement = orignalSoruce?.FindAscendant<TableViewCell>(); // Check if the pointer is over a cell
pressedElement ??= orignalSoruce?.FindAscendant<TableViewRow>(); // If not, check if the pointer is over a row
if (SelectionMode is ListViewSelectionMode.None // Skip selection when SelectionMode is None
|| IsDragSelecting // Skip selection when a drag is already in progress
|| orignalSoruce is ScrollBar // Skip selection when the pointer is over the ScrollBar
|| orignalSoruce?.FindAscendant<ScrollBar>() is { } // Skip selection when the pointer is within a ScrollBar
|| (pressedElement == null && !ShowDragRectangle) // Skip selection when the pointer is not over a Cell or Row, and ShowDragRectangle is false.
|| !pointerPoint.Properties.IsLeftButtonPressed // Skip selection when the left mouse button is not pressed
|| canvasPoint is null // Skip selection when canvasPoint is null (e.g., pointer is outside the scroll canvas)
|| canvasPoint.Value.Y < 0 // Skip selection when the pointer is in the column header area (above the scroll canvas)
|| (pressedElement == null && canvasPoint.Value.X < CellsHorizontalOffset) // Skip selection when the pointer is in the row header area (and not on a row/cell)
|| isShiftKey) // Skip selection when the Shift key is held
{
return;
}
_lastDragCanvasPoint = null;
CurrentCellSlot = null;
SelectionStartCellSlot = null;
SelectionStartRowIndex = null;
_lastDragSelectionRowRange = null;
_lastDragSelectionCellRange = null;
LastSelectionUnit = TableViewSelectionUnit.Row;
#if !WINDOWS
_dragStartCell = pressedElement as TableViewCell;
_dragStartRow = (pressedElement as TableViewRow) ?? orignalSoruce?.FindAscendant<TableViewRow>();
#endif
pressedElement ??= this; // If not, default to the TableView itself
SelectionStartCellSlot = (pressedElement as TableViewCell)?.Slot;
SelectionStartRowIndex = (pressedElement as TableViewRow)?.Index;
LastSelectionUnit = SelectionUnit switch
{
TableViewSelectionUnit.Cell => TableViewSelectionUnit.Cell,
TableViewSelectionUnit.Row => TableViewSelectionUnit.Row,
_ => pressedElement is TableViewCell
? TableViewSelectionUnit.Cell
: TableViewSelectionUnit.Row
};
if (SelectionMode is ListViewSelectionMode.Single)
{
_lastDragCanvasPoint = canvasPoint;
MakeSelectionInDragRect();
SetCurrentCell(GetSlotAtCanvasPoint(_lastDragCanvasPoint.Value));
return;
}
pressedElement.Focus(FocusState.Programmatic);
#if WINDOWS
_pointerCaptureElement = pressedElement;
#else
_pointerCaptureElement = this;
#endif
_pointerCaptureElement.CapturePointer(e.Pointer);
_tableViewDragPointer = e.Pointer;
if (!ctrlKey && SelectionMode is not ListViewSelectionMode.Multiple && LastSelectionUnit is not TableViewSelectionUnit.Cell)
DeselectAll();
StartDragSelection(canvasPoint.Value);
if (!IsDragSelecting)
{
_pointerCaptureElement?.ReleasePointerCaptures();
_pointerCaptureElement = null;
_tableViewDragPointer = null;
return;
}
MakeSelectionInDragRect();
}
/// <inheritdoc/>
protected override void OnPointerMoved(PointerRoutedEventArgs e)
{
base.OnPointerMoved(e);
if (!IsDragSelecting)
{
return;
}
var canvasPoint = GetCanvasPoint(e.GetCurrentPoint(this).Position);
if (canvasPoint is null)
{
return;
}
// Drive the rect visual for all drag sources (cell-initiated drags bubble pointer events here).
UpdateDragRectangleVisual(canvasPoint.Value);
// Selection-by-hit-test is only needed for TableView-initiated drags; cell-initiated
// drags perform selection in the cell's OnManipulationDelta via FindCell.
if (_tableViewDragPointer is not null)
{
MakeSelectionInDragRect();
}
}
/// <summary>
/// Makes selection based on the current drag rectangle, selecting either rows or cells depending on the last selection unit.
/// </summary>
private void MakeSelectionInDragRect()
{
if (LastSelectionUnit is not TableViewSelectionUnit.Cell)
{
if (GetRowsInDragRect() is ItemIndexRange rows)
{
SelectRowsInDragRect(rows);
}
else if (_lastDragSelectionRowRange?.Length > 0)
{
DeselectRange(_lastDragSelectionRowRange);
_lastDragSelectionRowRange = null;
SelectionStartRowIndex = null;
}
}
else if (LastSelectionUnit is not TableViewSelectionUnit.Row)
{
if (GetCellsInDragRect() is TableViewCellSlotRange cells)
{
SelectCellsInDragRect(cells);
}
else if (_lastDragSelectionCellRange?.Length > 0)
{
DeselectCellRange(_lastDragSelectionCellRange);
_lastDragSelectionCellRange = null;
SelectionStartCellSlot = null;
}
else if (!KeyboardHelper.IsCtrlKeyDown())
{
DeselectAllCells();
}
}
}
/// <summary>
/// Returns the range of cell slots covered by the current drag rectangle.
/// The first slot is the one nearest the drag start point and the last slot
/// is the one nearest the drag end point.
/// </summary>
private ItemIndexRange? GetRowsInDragRect()
{
if (_dragRectangle is null || _dragStartPoint is null || _lastDragCanvasPoint is null)
{
return null;
}
// Reconstruct the scroll-adjusted start corner the same way PositionDragRectangle does,
// so we know which corner of the rect corresponds to the drag origin.
var verticalScrollDelta = (_scrollViewer?.VerticalOffset ?? 0) - _dragStartVerticalOffset;
var startY = _dragStartPoint.Value.Y - verticalScrollDelta;
var endY = _lastDragCanvasPoint.Value.Y;
// Orientation of the drag, used to order the returned range from start to end.
var rowsTopToBottom = startY <= endY; ;
// Drag rect bounds in canvas space (already clamped and scroll-adjusted by PositionDragRectangle).
var rectTop = Canvas.GetTop(_dragRectangle);
var rectBottom = rectTop + _dragRectangle.Height;
// Find the min/max row indices whose bounds intersect the rect vertically.
var minRow = -1;
var maxRow = -1;
for (var rowIndex = 0; rowIndex < Items.Count; rowIndex++)
{
if (ContainerFromIndex(rowIndex) is not TableViewRow row)
{
continue;
}
var rowTop = row.Position.Y;
var rowBottom = rowTop + row.ActualHeight;
if (rowBottom <= rectTop || rowTop >= rectBottom)
{
continue;
}
if (minRow == -1) minRow = rowIndex;
maxRow = rowIndex;
}
if (minRow == -1)
{
return null;
}
// Use the anchor slot captured at drag start as the first slot. The visible scan above
// can't see rows/columns that auto-scroll has moved out of view (virtualized), so the
// anchor is the only reliable record of where the drag actually began.
if (SelectionStartRowIndex is { } anchor)
{
if (rowsTopToBottom) minRow = anchor;
else maxRow = anchor;
}
else
{
SelectionStartRowIndex = rowsTopToBottom ? minRow : maxRow;
}
return new ItemIndexRange(minRow, (uint)(maxRow - minRow + 1));
}
/// <summary>
/// Returns the range of cell slots covered by the current drag rectangle.
/// The first slot is the one nearest the drag start point and the last slot
/// is the one nearest the drag end point.
/// </summary>
private TableViewCellSlotRange? GetCellsInDragRect()
{
if (_dragRectangle is null || DragRectangleCanvas is null || _dragRectangle.Visibility != Visibility.Visible
|| _dragStartPoint is null || _lastDragCanvasPoint is null)
{
return null;
}
// Reconstruct the scroll-adjusted start corner the same way PositionDragRectangle does,
// so we know which corner of the rect corresponds to the drag origin.
var verticalScrollDelta = (_scrollViewer?.VerticalOffset ?? 0) - _dragStartVerticalOffset;
var horizontalScrollDelta = HorizontalOffset - _dragStartHorizontalOffset;
var startX = _dragStartPoint.Value.X - horizontalScrollDelta;
var startY = _dragStartPoint.Value.Y - verticalScrollDelta;
var endX = _lastDragCanvasPoint.Value.X;
var endY = _lastDragCanvasPoint.Value.Y;
// Orientation of the drag, used to order the returned range from start to end.
var rowsTopToBottom = startY <= endY;
var colsLeftToRight = startX <= endX;
// Drag rect bounds in canvas space (already clamped and scroll-adjusted by PositionDragRectangle).
var rectLeft = Canvas.GetLeft(_dragRectangle);
var rectRight = rectLeft + _dragRectangle.Width;
var rows = GetRowsInDragRect();
if (rows is null || rows.Length == 0) return null;
// Find the min/max row indices whose bounds intersect the rect vertically.
var minRow = rows.FirstIndex;
var maxRow = rows.LastIndex;
// Find the min/max column indices whose bounds intersect the rect horizontally.
// Frozen columns are pinned and don't scroll; non-frozen columns shift with HorizontalOffset.
// Non-frozen columns that scroll behind the frozen panel are not selectable from that area.
var minColumn = -1;
var maxColumn = -1;
var frozenCount = FrozenColumnCount;
var columnLeft = CellsHorizontalOffset;
var frozenPanelRight = CellsHorizontalOffset; // updated when we cross into non-frozen territory
for (var colIndex = 0; colIndex < Columns.VisibleColumns.Count; colIndex++)
{
if (colIndex == frozenCount)
{
frozenPanelRight = columnLeft;
columnLeft -= HorizontalOffset;
}
var columnRight = columnLeft + Columns.VisibleColumns[colIndex].ActualWidth;
// Clamp non-frozen columns to the visible area past the frozen panel.
var effectiveLeft = colIndex >= frozenCount ? Math.Max(columnLeft, frozenPanelRight) : columnLeft;
if (columnRight > rectLeft && effectiveLeft < rectRight)
{
if (minColumn == -1) minColumn = colIndex;
maxColumn = colIndex;
}
columnLeft = columnRight;
}
if (minColumn == -1)
{
return null;
}
// Use the anchor slot captured at drag start as the first slot. The visible scan above
// can't see rows/columns that auto-scroll has moved out of view (virtualized), so the
// anchor is the only reliable record of where the drag actually began.
if (SelectionStartCellSlot is { } anchor)
{
if (rowsTopToBottom) minRow = anchor.Row;
else maxRow = anchor.Row;
if (colsLeftToRight) minColumn = anchor.Column;
else maxColumn = anchor.Column;
}
else
{
var startCol = colsLeftToRight ? minColumn : maxColumn;
SelectionStartCellSlot = new(SelectionStartRowIndex ?? minRow, startCol);
}
return TableViewCellSlotRange.FromSlots(new(minRow, minColumn), new(maxRow, maxColumn));
}
/// <summary>
/// Selects rows that intersect with the current drag rectangle, updating the selection state accordingly.
/// </summary>
private void SelectRowsInDragRect(ItemIndexRange rows)
{
if (_lastDragSelectionRowRange?.FirstIndex == rows.FirstIndex && _lastDragSelectionRowRange?.LastIndex == rows.LastIndex) return;
if (SelectionMode is ListViewSelectionMode.Single && rows.Length is 1)
{
SelectedIndex = rows.FirstIndex;
}
else if (_lastDragSelectionRowRange is not null && _lastDragSelectionRowRange.Contains(rows))
{
foreach (var slicedRange in _lastDragSelectionRowRange.Subtract(rows))
{
DeselectRange(slicedRange);
}
}
else if (rows.Length > 0)
{
SelectRange(rows);
}
_lastDragSelectionRowRange = rows;
}
/// <summary>
/// Selects cells that intersect with the current drag rectangle, updating the selection state accordingly.
/// </summary>
private void SelectCellsInDragRect(TableViewCellSlotRange cells)
{
if (_lastDragSelectionCellRange == cells) return;
DispatcherQueue.TryEnqueue(() =>
{
if (_lastDragSelectionCellRange is null
&& !KeyboardHelper.IsCtrlKeyDown()
&& SelectionMode is not ListViewSelectionMode.Multiple)
{
DeselectAllItems();
SelectedCellRanges.Clear();
}
else if (_lastDragSelectionCellRange is not null && cells is not null)
{
foreach (var range in _lastDragSelectionCellRange.Subtract(cells))
{
SubtractCellRangeFromSelection(range);
}
}
if (SelectedCellRanges.Any(r => r == cells))
{
OnCellSelectionChanged();
}
else if (cells?.Length > 0)
{
SelectCellRange(cells);
}
_lastDragSelectionCellRange = cells;
});
}
/// <summary>
/// Handles pointer-released for all cases, including when elements sets <c>e.Handled = true</c>.
/// </summary>
private void OnAnyPointerReleased(object sender, PointerRoutedEventArgs e)
{
EndDragSelection();
}
/// <summary>
/// Handles navigation keys.
/// </summary>
private void HandleNavigations(KeyRoutedEventArgs e, bool shiftKey, bool ctrlKey)
{
var currentCell = CurrentCellSlot.HasValue ? GetCellFromSlot(CurrentCellSlot.Value) : default;
if (e.Key is VirtualKey.F2 && currentCell is { IsReadOnly: false } && !IsEditing)
{
e.Handled = currentCell.BeginCellEditing(e);
}
else if (e.Key is VirtualKey.Escape && currentCell is not null && IsEditing)
{
// Transfer focus from the editing element (e.g. TextBox) to the cell
// itself BEFORE EndCellEditing tears down that element. If we wait,
// WinUI's focus manager will move focus to the next focusable sibling
// the moment the editing element is removed from the visual tree, and
// screen readers will announce that sibling instead of the current cell.
currentCell.Focus(FocusState.Programmatic);
e.Handled = EndCellEditing(TableViewEditAction.Cancel, currentCell);
SetIsEditing(false);
}
else if (e.Key is VirtualKey.Space && currentCell is not null && CurrentCellSlot.HasValue && !IsEditing)
{
if (!currentCell.IsSelected)
{
MakeSelection(CurrentCellSlot.Value, shiftKey, ctrlKey);
}
else
{
DeselectCell(CurrentCellSlot.Value);
}
}
// Handle navigation keys
else if (e.Key is VirtualKey.Tab or VirtualKey.Enter)
{
var isEditing = IsEditing;
var newSlot = CurrentCellSlot ?? new();
do
{
newSlot = GetNextSlot(newSlot, shiftKey, e.Key is VirtualKey.Enter);
} while (isEditing && Columns[newSlot.Column].IsReadOnly);
if (isEditing && currentCell is not null)
{
if (!EndCellEditing(TableViewEditAction.Commit, currentCell)) return;
if (CurrentCellSlot == newSlot || GetCellFromSlot(newSlot) is not { } nextCell || !nextCell.BeginCellEditing(e))
{
SetIsEditing(false);
}
}
MakeSelection(newSlot, false);
e.Handled = true;
}
else if ((e.Key is VirtualKey.Left or VirtualKey.Right or VirtualKey.Up or VirtualKey.Down)
&& !IsEditing)
{
var row = (LastSelectionUnit is TableViewSelectionUnit.Row ? CurrentRowIndex : CurrentCellSlot?.Row) ?? -1;
var column = CurrentCellSlot?.Column ?? -1;
if (row == -1 && column == -1)
{
row = column = 0;
}
else if (e.Key is VirtualKey.Left or VirtualKey.Right)
{
column = e.Key is VirtualKey.Left ? ctrlKey ? 0 : column - 1 : ctrlKey ? Columns.VisibleColumns.Count - 1 : column + 1;
if (column >= Columns.VisibleColumns.Count)
{
column = 0;
row++;
}
}
else
{
row = e.Key == VirtualKey.Up ? ctrlKey ? 0 : row - 1 : ctrlKey ? Items.Count - 1 : row + 1;
}
var newSlot = new TableViewCellSlot(row, column);
MakeSelection(newSlot, shiftKey);
e.Handled = true;
}
else if (e.Key is VirtualKey.Home or VirtualKey.End)
{
var row = ctrlKey ? (e.Key == VirtualKey.Home ? 0 : _collectionView.Count - 1) : CurrentCellSlot?.Row;
var column = e.Key == VirtualKey.Home ? 0 : Columns.VisibleColumns.Count - 1;
var newSlot = new TableViewCellSlot(row ?? -1, column);
MakeSelection(newSlot, shiftKey);
e.Handled = true;
}
else if (e.Key is VirtualKey.PageDown or VirtualKey.PageUp)
{
var pageSize = CalculateAvailablePageSize();
var row = (LastSelectionUnit is TableViewSelectionUnit.Row ? CurrentRowIndex : CurrentCellSlot?.Row) ?? -1;
var column = CurrentCellSlot?.Column ?? -1;
var numRows = CollectionView.Count;
var nextRow = e.Key == VirtualKey.PageDown
? Math.Min(numRows - 1, row + pageSize)
: Math.Max(0, row - pageSize);
var newSlot = new TableViewCellSlot(nextRow, column);
MakeSelection(newSlot, shiftKey);
e.Handled = true;
}
}
/// <summary>
/// Calculates how many rows should be able to fit within the actual height of the table without scrolling.
/// </summary>
private int CalculateAvailablePageSize()
{
var rowHeight = RowHeight is not double.NaN ? RowHeight : RowMinHeight;
var headerHeight = HeaderRowHeight is not double.NaN ? HeaderRowHeight : HeaderRowMinHeight;
var availableHeight = ActualHeight - headerHeight;
return (int)Math.Floor(availableHeight / rowHeight);
}
/// <summary>
/// Ends the editing of a cell, committing or canceling the edit based on the specified action.
/// </summary>
internal bool EndCellEditing(TableViewEditAction editAction, TableViewCell cell)
{
var editingElement = cell.Content as FrameworkElement;
var endingArgs = new TableViewCellEditEndingEventArgs(cell, cell.Row?.Content, cell.Column!, editingElement!, editAction);
OnCellEditEnding(endingArgs);
if (endingArgs.Cancel)
{
return false;
}
cell.EndEditing(editAction);
var endArgs = new TableViewCellEditEndedEventArgs(cell, cell.Row?.Content, cell.Column!, editAction);
OnCellEditEnded(endArgs);
return true;
}
/// <summary>
/// Handles shortcut keys.
/// </summary>
private bool HandleShortKeys(bool shiftKey, bool ctrlKey, VirtualKey key)
{
if (key == VirtualKey.A && ctrlKey && !shiftKey)
{
SelectAll();
return true;
}
else if (key == VirtualKey.A && ctrlKey && shiftKey)
{
DeselectAll();
return true;
}
else if (key == VirtualKey.C && ctrlKey)
{
CopyToClipboardInternal(shiftKey);
return true;
}
else if (key == VirtualKey.V && ctrlKey && !shiftKey)
{
return TryStartPasteFromClipboard();
}
return false;
}
/// <inheritdoc/>
protected async override void OnApplyTemplate()
{
base.OnApplyTemplate();
_headerRow = GetTemplateChild("HeaderRow") as TableViewHeaderRow;
_scrollViewer = GetTemplateChild("ScrollViewer") as ScrollViewer;
_headerRowDefinition = GetTemplateChild("HeaderRowDefinition") as RowDefinition;