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 pathDataGrid.cs
More file actions
9219 lines (8096 loc) · 375 KB
/
DataGrid.cs
File metadata and controls
9219 lines (8096 loc) · 375 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;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Diagnostics;
using System.Security;
using System.Text;
using Microsoft.Toolkit.Uwp.UI.Automation.Peers;
using Microsoft.Toolkit.Uwp.UI.Controls.DataGridInternals;
using Microsoft.Toolkit.Uwp.UI.Controls.Primitives;
using Microsoft.Toolkit.Uwp.UI.Controls.Utilities;
using Microsoft.Toolkit.Uwp.UI.Data.Utilities;
using Microsoft.Toolkit.Uwp.UI.Utilities;
using Microsoft.Toolkit.Uwp.Utilities;
using Windows.ApplicationModel.DataTransfer;
using Windows.Devices.Input;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.System;
using Windows.UI.Input;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Automation.Peers;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Media.Animation;
using DiagnosticsDebug = System.Diagnostics.Debug;
namespace Microsoft.Toolkit.Uwp.UI.Controls
{
/// <summary>
/// Control to represent data in columns and rows.
/// </summary>
#if FEATURE_VALIDATION_SUMMARY
[TemplatePart(Name = DataGrid.DATAGRID_elementValidationSummary, Type = typeof(ValidationSummary))]
#endif
[TemplatePart(Name = DataGrid.DATAGRID_elementRowsPresenterName, Type = typeof(DataGridRowsPresenter))]
[TemplatePart(Name = DataGrid.DATAGRID_elementColumnHeadersPresenterName, Type = typeof(DataGridColumnHeadersPresenter))]
[TemplatePart(Name = DataGrid.DATAGRID_elementFrozenColumnScrollBarSpacerName, Type = typeof(FrameworkElement))]
[TemplatePart(Name = DataGrid.DATAGRID_elementHorizontalScrollBarName, Type = typeof(ScrollBar))]
[TemplatePart(Name = DataGrid.DATAGRID_elementVerticalScrollBarName, Type = typeof(ScrollBar))]
[TemplateVisualState(Name = VisualStates.StateDisabled, GroupName = VisualStates.GroupCommon)]
[TemplateVisualState(Name = VisualStates.StateNormal, GroupName = VisualStates.GroupCommon)]
[TemplateVisualState(Name = VisualStates.StateTouchIndicator, GroupName = VisualStates.GroupScrollBars)]
[TemplateVisualState(Name = VisualStates.StateMouseIndicator, GroupName = VisualStates.GroupScrollBars)]
[TemplateVisualState(Name = VisualStates.StateMouseIndicatorFull, GroupName = VisualStates.GroupScrollBars)]
[TemplateVisualState(Name = VisualStates.StateNoIndicator, GroupName = VisualStates.GroupScrollBars)]
[TemplateVisualState(Name = VisualStates.StateSeparatorExpanded, GroupName = VisualStates.GroupScrollBarsSeparator)]
[TemplateVisualState(Name = VisualStates.StateSeparatorCollapsed, GroupName = VisualStates.GroupScrollBarsSeparator)]
[TemplateVisualState(Name = VisualStates.StateSeparatorExpandedWithoutAnimation, GroupName = VisualStates.GroupScrollBarsSeparator)]
[TemplateVisualState(Name = VisualStates.StateSeparatorCollapsedWithoutAnimation, GroupName = VisualStates.GroupScrollBarsSeparator)]
[TemplateVisualState(Name = VisualStates.StateInvalid, GroupName = VisualStates.GroupValidation)]
[TemplateVisualState(Name = VisualStates.StateValid, GroupName = VisualStates.GroupValidation)]
[StyleTypedProperty(Property = "CellStyle", StyleTargetType = typeof(DataGridCell))]
[StyleTypedProperty(Property = "ColumnHeaderStyle", StyleTargetType = typeof(DataGridColumnHeader))]
[StyleTypedProperty(Property = "DragIndicatorStyle", StyleTargetType = typeof(ContentControl))]
[StyleTypedProperty(Property = "DropLocationIndicatorStyle", StyleTargetType = typeof(Control))]
[StyleTypedProperty(Property = "RowHeaderStyle", StyleTargetType = typeof(DataGridRowHeader))]
[StyleTypedProperty(Property = "RowStyle", StyleTargetType = typeof(DataGridRow))]
public partial class DataGrid : Control
{
private enum ScrollBarVisualState
{
NoIndicator,
TouchIndicator,
MouseIndicator,
MouseIndicatorFull
}
private enum ScrollBarsSeparatorVisualState
{
SeparatorCollapsed,
SeparatorExpanded,
SeparatorExpandedWithoutAnimation,
SeparatorCollapsedWithoutAnimation
}
#if FEATURE_VALIDATION_SUMMARY
private const string DATAGRID_elementValidationSummary = "ValidationSummary";
#endif
private const string DATAGRID_elementRootName = "Root";
private const string DATAGRID_elementRowsPresenterName = "RowsPresenter";
private const string DATAGRID_elementColumnHeadersPresenterName = "ColumnHeadersPresenter";
private const string DATAGRID_elementFrozenColumnScrollBarSpacerName = "FrozenColumnScrollBarSpacer";
private const string DATAGRID_elementHorizontalScrollBarName = "HorizontalScrollBar";
private const string DATAGRID_elementRowHeadersPresenterName = "RowHeadersPresenter";
private const string DATAGRID_elementTopLeftCornerHeaderName = "TopLeftCornerHeader";
private const string DATAGRID_elementTopRightCornerHeaderName = "TopRightCornerHeader";
private const string DATAGRID_elementBottomRightCornerHeaderName = "BottomRightCorner";
private const string DATAGRID_elementVerticalScrollBarName = "VerticalScrollBar";
private const bool DATAGRID_defaultAutoGenerateColumns = true;
private const bool DATAGRID_defaultCanUserReorderColumns = true;
private const bool DATAGRID_defaultCanUserResizeColumns = true;
private const bool DATAGRID_defaultCanUserSortColumns = true;
private const DataGridGridLinesVisibility DATAGRID_defaultGridLinesVisibility = DataGridGridLinesVisibility.None;
private const DataGridHeadersVisibility DATAGRID_defaultHeadersVisibility = DataGridHeadersVisibility.Column;
private const DataGridRowDetailsVisibilityMode DATAGRID_defaultRowDetailsVisibility = DataGridRowDetailsVisibilityMode.VisibleWhenSelected;
private const DataGridSelectionMode DATAGRID_defaultSelectionMode = DataGridSelectionMode.Extended;
private const ScrollBarVisibility DATAGRID_defaultScrollBarVisibility = ScrollBarVisibility.Auto;
/// <summary>
/// The default order to use for columns when there is no <see cref="DisplayAttribute.Order"/>
/// value available for the property.
/// </summary>
/// <remarks>
/// The value of 10,000 comes from the DataAnnotations spec, allowing
/// some properties to be ordered at the beginning and some at the end.
/// </remarks>
private const int DATAGRID_defaultColumnDisplayOrder = 10000;
private const double DATAGRID_horizontalGridLinesThickness = 1;
private const double DATAGRID_minimumRowHeaderWidth = 4;
private const double DATAGRID_minimumColumnHeaderHeight = 4;
internal const double DATAGRID_maximumStarColumnWidth = 10000;
internal const double DATAGRID_minimumStarColumnWidth = 0.001;
private const double DATAGRID_mouseWheelDeltaDivider = 4.0;
private const double DATAGRID_maxHeadersThickness = 32768;
private const double DATAGRID_defaultRowHeight = 22;
internal const double DATAGRID_defaultRowGroupSublevelIndent = 20;
private const double DATAGRID_defaultMinColumnWidth = 20;
private const double DATAGRID_defaultMaxColumnWidth = double.PositiveInfinity;
private const double DATAGRID_defaultIncrementalLoadingThreshold = 3.0;
private const double DATAGRID_defaultDataFetchSize = 3.0;
// 2 seconds delay used to hide the scroll bars for example when OS animations are turned off.
private const int DATAGRID_noScrollBarCountdownMs = 2000;
// Used to work around double arithmetic rounding.
private const double DATAGRID_roundingDelta = 0.0001;
// DataGrid Template Parts
#if FEATURE_VALIDATION_SUMMARY
private ValidationSummary _validationSummary;
#endif
private UIElement _bottomRightCorner;
private DataGridColumnHeadersPresenter _columnHeadersPresenter;
private ScrollBar _hScrollBar;
private DataGridRowsPresenter _rowsPresenter;
private ScrollBar _vScrollBar;
private byte _autoGeneratingColumnOperationCount;
private bool _autoSizingColumns;
private List<ValidationResult> _bindingValidationResults;
private ContentControl _clipboardContentControl;
private IndexToValueTable<Visibility> _collapsedSlotsTable;
private bool _columnHeaderHasFocus;
private DataGridCellCoordinates _currentCellCoordinates;
// used to store the current column during a Reset
private int _desiredCurrentColumnIndex;
private int _editingColumnIndex;
private RoutedEventArgs _editingEventArgs;
private bool _executingLostFocusActions;
private bool _flushCurrentCellChanged;
private bool _focusEditingControl;
private FocusInputDeviceKind _focusInputDevice;
private DependencyObject _focusedObject;
private DataGridRow _focusedRow;
private FrameworkElement _frozenColumnScrollBarSpacer;
private bool _hasNoIndicatorStateStoryboardCompletedHandler;
private DispatcherQueueTimer _hideScrollBarsTimer;
// the sum of the widths in pixels of the scrolling columns preceding
// the first displayed scrolling column
private double _horizontalOffset;
private byte _horizontalScrollChangesIgnored;
private bool _ignoreNextScrollBarsLayout;
private List<ValidationResult> _indeiValidationResults;
private bool _initializingNewItem;
private bool _isHorizontalScrollBarInteracting;
private bool _isVerticalScrollBarInteracting;
// Set to True when the pointer is over the optional scroll bars.
private bool _isPointerOverHorizontalScrollBar;
private bool _isPointerOverVerticalScrollBar;
// Set to True to prevent the normal fade-out of the scroll bars.
private bool _keepScrollBarsShowing;
// Nth row of rows 0..N that make up the RowHeightEstimate
private int _lastEstimatedRow;
private List<DataGridRow> _loadedRows;
// prevents reentry into the VerticalScroll event handler
private Queue<Action> _lostFocusActions;
private bool _makeFirstDisplayedCellCurrentCellPending;
private bool _measured;
// the number of pixels of the firstDisplayedScrollingCol which are not displayed
private double _negHorizontalOffset;
// the number of pixels of DisplayData.FirstDisplayedScrollingRow which are not displayed
private int _noCurrentCellChangeCount;
private int _noFocusedColumnChangeCount;
private int _noSelectionChangeCount;
private double _oldEdgedRowsHeightCalculated = 0.0;
// Set to True to favor mouse indicators over panning indicators for the scroll bars.
private bool _preferMouseIndicators;
private DataGridCellCoordinates _previousAutomationFocusCoordinates;
private DataGridColumn _previousCurrentColumn;
private object _previousCurrentItem;
private List<ValidationResult> _propertyValidationResults;
private ScrollBarVisualState _proposedScrollBarsState;
private ScrollBarsSeparatorVisualState _proposedScrollBarsSeparatorState;
private string _rowGroupHeaderPropertyNameAlternative;
private ObservableCollection<Style> _rowGroupHeaderStyles;
// To figure out what the old RowGroupHeaderStyle was for each level, we need to keep a copy
// of the list. The old style important so we don't blow away styles set directly on the RowGroupHeader
private List<Style> _rowGroupHeaderStylesOld;
private double[] _rowGroupHeightsByLevel;
private double _rowHeaderDesiredWidth;
private Size? _rowsPresenterAvailableSize;
private bool _scrollingByHeight;
private DataGridSelectedItemsCollection _selectedItems;
private IndexToValueTable<Visibility> _showDetailsTable;
// Set to True when the mouse scroll bars are currently showing.
private bool _showingMouseIndicators;
private bool _successfullyUpdatedSelection;
private bool _temporarilyResetCurrentCell;
private bool _isUserSorting; // True if we're currently in a user invoked sorting operation
private ContentControl _topLeftCornerHeader;
private ContentControl _topRightCornerHeader;
private object _uneditedValue; // Represents the original current cell value at the time it enters editing mode.
private string _updateSourcePath;
private Dictionary<INotifyDataErrorInfo, string> _validationItems;
private List<ValidationResult> _validationResults;
private byte _verticalScrollChangesIgnored;
#if FEATURE_ICOLLECTIONVIEW_GROUP
private INotifyCollectionChanged _topLevelGroup;
#else
private IObservableVector<object> _topLevelGroup;
#endif
#if FEATURE_VALIDATION_SUMMARY
private ValidationSummaryItem _selectedValidationSummaryItem;
#endif
// An approximation of the sum of the heights in pixels of the scrolling rows preceding
// the first displayed scrolling row. Since the scrolled off rows are discarded, the grid
// does not know their actual height. The heights used for the approximation are the ones
// set as the rows were scrolled off.
private double _verticalOffset;
#if FEATURE_ICOLLECTIONVIEW_GROUP
// Cache event listeners for PropertyChanged and CollectionChanged events from CollectionViewGroups
private Dictionary<INotifyPropertyChanged, WeakEventListener<DataGrid, object, PropertyChangedEventArgs>> _groupsPropertyChangedListenersTable = new Dictionary<INotifyPropertyChanged, WeakEventListener<DataGrid, object, PropertyChangedEventArgs>>();
private Dictionary<INotifyCollectionChanged, WeakEventListener<DataGrid, object, NotifyCollectionChangedEventArgs>> _groupsCollectionChangedListenersTable = new Dictionary<INotifyCollectionChanged, WeakEventListener<DataGrid, object, NotifyCollectionChangedEventArgs>>();
#else
// Cache event listeners for VectorChanged events from ICollectionViewGroup's GroupItems
private Dictionary<IObservableVector<object>, WeakEventListener<DataGrid, object, IVectorChangedEventArgs>> _groupsVectorChangedListenersTable = new Dictionary<IObservableVector<object>, WeakEventListener<DataGrid, object, IVectorChangedEventArgs>>();
#endif
/// <summary>
/// Occurs one time for each public, non-static property in the bound data type when the
/// <see cref="ItemsSource"/> property is changed and the
/// <see cref="AutoGenerateColumns"/> property is true.
/// </summary>
public event EventHandler<DataGridAutoGeneratingColumnEventArgs> AutoGeneratingColumn;
/// <summary>
/// Occurs before a cell or row enters editing mode.
/// </summary>
public event EventHandler<DataGridBeginningEditEventArgs> BeginningEdit;
/// <summary>
/// Occurs after cell editing has ended.
/// </summary>
public event EventHandler<DataGridCellEditEndedEventArgs> CellEditEnded;
/// <summary>
/// Occurs immediately before cell editing has ended.
/// </summary>
public event EventHandler<DataGridCellEditEndingEventArgs> CellEditEnding;
/// <summary>
/// Occurs when the <see cref="Microsoft.Toolkit.Uwp.UI.Controls.DataGridColumn.DisplayIndex"/>
/// property of a column changes.
/// </summary>
public event EventHandler<DataGridColumnEventArgs> ColumnDisplayIndexChanged;
/// <summary>
/// Occurs when the user drops a column header that was being dragged using the mouse.
/// </summary>
public event EventHandler<DragCompletedEventArgs> ColumnHeaderDragCompleted;
/// <summary>
/// Occurs one or more times while the user drags a column header using the mouse.
/// </summary>
public event EventHandler<DragDeltaEventArgs> ColumnHeaderDragDelta;
/// <summary>
/// Occurs when the user begins dragging a column header using the mouse.
/// </summary>
public event EventHandler<DragStartedEventArgs> ColumnHeaderDragStarted;
/// <summary>
/// Raised when column reordering ends, to allow subscribers to clean up.
/// </summary>
public event EventHandler<DataGridColumnEventArgs> ColumnReordered;
/// <summary>
/// Raised when starting a column reordering action. Subscribers to this event can
/// set tooltip and caret UIElements, constrain tooltip position, indicate that
/// a preview should be shown, or cancel reordering.
/// </summary>
public event EventHandler<DataGridColumnReorderingEventArgs> ColumnReordering;
/// <summary>
/// This event is raised by OnCopyingRowClipboardContent method after the default row content is prepared.
/// Event listeners can modify or add to the row clipboard content.
/// </summary>
public event EventHandler<DataGridRowClipboardEventArgs> CopyingRowClipboardContent;
/// <summary>
/// Occurs when a different cell becomes the current cell.
/// </summary>
public event EventHandler<EventArgs> CurrentCellChanged;
/// <summary>
/// Occurs after a <see cref="DataGridRow"/>
/// is instantiated, so that you can customize it before it is used.
/// </summary>
public event EventHandler<DataGridRowEventArgs> LoadingRow;
/// <summary>
/// Occurs when a new row details template is applied to a row, so that you can customize
/// the details section before it is used.
/// </summary>
public event EventHandler<DataGridRowDetailsEventArgs> LoadingRowDetails;
/// <summary>
/// Occurs before a DataGridRowGroupHeader header is used.
/// </summary>
public event EventHandler<DataGridRowGroupHeaderEventArgs> LoadingRowGroup;
/// <summary>
/// Occurs when a cell in a <see cref="DataGridTemplateColumn"/> enters editing mode.
/// </summary>
public event EventHandler<DataGridPreparingCellForEditEventArgs> PreparingCellForEdit;
/// <summary>
/// Occurs when the <see cref="RowDetailsVisibilityMode"/>
/// property value changes.
/// </summary>
public event EventHandler<DataGridRowDetailsEventArgs> RowDetailsVisibilityChanged;
/// <summary>
/// Occurs when the row has been successfully committed or canceled.
/// </summary>
public event EventHandler<DataGridRowEditEndedEventArgs> RowEditEnded;
/// <summary>
/// Occurs immediately before the row has been successfully committed or canceled.
/// </summary>
public event EventHandler<DataGridRowEditEndingEventArgs> RowEditEnding;
/// <summary>
/// Occurs when the <see cref="SelectedItem"/> or
/// <see cref="SelectedItems"/> property value changes.
/// </summary>
public event SelectionChangedEventHandler SelectionChanged;
/// <summary>
/// Occurs when the <see cref="Microsoft.Toolkit.Uwp.UI.Controls.DataGridColumn"/> sorting request is triggered.
/// </summary>
public event EventHandler<DataGridColumnEventArgs> Sorting;
/// <summary>
/// Occurs when a <see cref="DataGridRow"/>
/// object becomes available for reuse.
/// </summary>
public event EventHandler<DataGridRowEventArgs> UnloadingRow;
/// <summary>
/// Occurs when the DataGridRowGroupHeader is available for reuse.
/// </summary>
public event EventHandler<DataGridRowGroupHeaderEventArgs> UnloadingRowGroup;
/// <summary>
/// Occurs when a row details element becomes available for reuse.
/// </summary>
public event EventHandler<DataGridRowDetailsEventArgs> UnloadingRowDetails;
/// <summary>
/// Initializes a new instance of the <see cref="DataGrid"/> class.
/// </summary>
public DataGrid()
{
this.TabNavigation = KeyboardNavigationMode.Once;
_loadedRows = new List<DataGridRow>();
_lostFocusActions = new Queue<Action>();
_selectedItems = new DataGridSelectedItemsCollection(this);
_rowGroupHeaderPropertyNameAlternative = Controls.Resources.DefaultRowGroupHeaderPropertyNameAlternative;
_rowGroupHeaderStyles = new ObservableCollection<Style>();
_rowGroupHeaderStyles.CollectionChanged += RowGroupHeaderStyles_CollectionChanged;
_rowGroupHeaderStylesOld = new List<Style>();
this.RowGroupHeadersTable = new IndexToValueTable<DataGridRowGroupInfo>();
_collapsedSlotsTable = new IndexToValueTable<Visibility>();
_validationItems = new Dictionary<INotifyDataErrorInfo, string>();
_validationResults = new List<ValidationResult>();
_bindingValidationResults = new List<ValidationResult>();
_propertyValidationResults = new List<ValidationResult>();
_indeiValidationResults = new List<ValidationResult>();
this.ColumnHeaderInteractionInfo = new DataGridColumnHeaderInteractionInfo();
this.DisplayData = new DataGridDisplayData(this);
this.ColumnsInternal = CreateColumnsInstance();
this.RowHeightEstimate = DATAGRID_defaultRowHeight;
this.RowDetailsHeightEstimate = 0;
_rowHeaderDesiredWidth = 0;
this.DataConnection = new DataGridDataConnection(this);
_showDetailsTable = new IndexToValueTable<Visibility>();
_focusInputDevice = FocusInputDeviceKind.None;
_proposedScrollBarsState = ScrollBarVisualState.NoIndicator;
_proposedScrollBarsSeparatorState = ScrollBarsSeparatorVisualState.SeparatorCollapsed;
this.AnchorSlot = -1;
_lastEstimatedRow = -1;
_editingColumnIndex = -1;
this.CurrentCellCoordinates = new DataGridCellCoordinates(-1, -1);
this.RowGroupHeaderHeightEstimate = DATAGRID_defaultRowHeight;
this.LastHandledKeyDown = VirtualKey.None;
this.DefaultStyleKey = typeof(DataGrid);
ActualThemeChanged += this.DataGrid_ActualThemeChanged;
HookDataGridEvents();
}
private void DataGrid_ActualThemeChanged(FrameworkElement sender, object args)
{
DataGrid dataGrid = sender as DataGrid;
foreach (DataGridRow row in dataGrid.GetAllRows())
{
row.EnsureBackground();
row.EnsureForeground();
}
}
/// <summary>
/// Gets or sets the <see cref="T:System.Windows.Media.Brush"/> that is used to paint the background of odd-numbered rows.
/// </summary>
/// <returns>
/// The brush that is used to paint the background of odd-numbered rows.
/// </returns>
public Brush AlternatingRowBackground
{
get { return GetValue(AlternatingRowBackgroundProperty) as Brush; }
set { SetValue(AlternatingRowBackgroundProperty, value); }
}
/// <summary>
/// Identifies the <see cref="AlternatingRowBackground"/>
/// dependency property.
/// </summary>
/// <returns>
/// The identifier for the <see cref="AlternatingRowBackground"/>
/// dependency property.
/// </returns>
public static readonly DependencyProperty AlternatingRowBackgroundProperty =
DependencyProperty.Register(
"AlternatingRowBackground",
typeof(Brush),
typeof(DataGrid),
new PropertyMetadata(null, OnAlternatingRowBackgroundPropertyChanged));
private static void OnAlternatingRowBackgroundPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
DataGrid dataGrid = d as DataGrid;
foreach (DataGridRow row in dataGrid.GetAllRows())
{
row.EnsureBackground();
}
}
/// <summary>
/// Gets or sets the <see cref="T:System.Windows.Media.Brush"/> that is used to paint the foreground of odd-numbered rows.
/// </summary>
/// <returns>
/// The brush that is used to paint the foreground of odd-numbered rows.
/// </returns>
public Brush AlternatingRowForeground
{
get { return GetValue(AlternatingRowForegroundProperty) as Brush; }
set { SetValue(AlternatingRowForegroundProperty, value); }
}
/// <summary>
/// Identifies the <see cref="AlternatingRowForeground"/>
/// dependency property.
/// </summary>
/// <returns>
/// The identifier for the <see cref="AlternatingRowForeground"/>
/// dependency property.
/// </returns>
public static readonly DependencyProperty AlternatingRowForegroundProperty =
DependencyProperty.Register(
"AlternatingRowForeground",
typeof(Brush),
typeof(DataGrid),
new PropertyMetadata(null, OnAlternatingRowForegroundPropertyChanged));
private static void OnAlternatingRowForegroundPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
DataGrid dataGrid = d as DataGrid;
foreach (DataGridRow row in dataGrid.GetAllRows())
{
row.EnsureForeground();
}
}
/// <summary>
/// Gets or sets a value indicating whether the row details sections remain
/// fixed at the width of the display area or can scroll horizontally.
/// </summary>
public bool AreRowDetailsFrozen
{
get { return (bool)GetValue(AreRowDetailsFrozenProperty); }
set { SetValue(AreRowDetailsFrozenProperty, value); }
}
/// <summary>
/// Identifies the AreRowDetailsFrozen dependency property.
/// </summary>
public static readonly DependencyProperty AreRowDetailsFrozenProperty =
DependencyProperty.Register(
"AreRowDetailsFrozen",
typeof(bool),
typeof(DataGrid),
null);
/// <summary>
/// Gets or sets a value indicating whether the row group header sections
/// remain fixed at the width of the display area or can scroll horizontally.
/// </summary>
public bool AreRowGroupHeadersFrozen
{
get { return (bool)GetValue(AreRowGroupHeadersFrozenProperty); }
set { SetValue(AreRowGroupHeadersFrozenProperty, value); }
}
/// <summary>
/// Identifies the AreRowDetailsFrozen dependency property.
/// </summary>
public static readonly DependencyProperty AreRowGroupHeadersFrozenProperty =
DependencyProperty.Register(
"AreRowGroupHeadersFrozen",
typeof(bool),
typeof(DataGrid),
new PropertyMetadata(true, OnAreRowGroupHeadersFrozenPropertyChanged));
private static void OnAreRowGroupHeadersFrozenPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
DataGrid dataGrid = d as DataGrid;
ProcessFrozenColumnCount(dataGrid);
// Update elements in the RowGroupHeader that were previously frozen.
if ((bool)e.NewValue)
{
if (dataGrid._rowsPresenter != null)
{
foreach (UIElement element in dataGrid._rowsPresenter.Children)
{
DataGridRowGroupHeader groupHeader = element as DataGridRowGroupHeader;
if (groupHeader != null)
{
groupHeader.ClearFrozenStates();
}
}
}
}
}
/// <summary>
/// Gets or sets a value indicating whether columns are created
/// automatically when the <see cref="ItemsSource"/> property is set.
/// </summary>
public bool AutoGenerateColumns
{
get { return (bool)GetValue(AutoGenerateColumnsProperty); }
set { SetValue(AutoGenerateColumnsProperty, value); }
}
/// <summary>
/// Identifies the AutoGenerateColumns dependency property.
/// </summary>
public static readonly DependencyProperty AutoGenerateColumnsProperty =
DependencyProperty.Register(
"AutoGenerateColumns",
typeof(bool),
typeof(DataGrid),
new PropertyMetadata(DATAGRID_defaultAutoGenerateColumns, OnAutoGenerateColumnsPropertyChanged));
private static void OnAutoGenerateColumnsPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
DataGrid dataGrid = d as DataGrid;
bool value = (bool)e.NewValue;
if (value)
{
dataGrid.InitializeElements(false /*recycleRows*/);
}
else
{
dataGrid.RemoveAutoGeneratedColumns();
}
}
/// <summary>
/// Gets or sets a value indicating whether the user can change
/// the column display order by dragging column headers with the mouse.
/// </summary>
public bool CanUserReorderColumns
{
get { return (bool)GetValue(CanUserReorderColumnsProperty); }
set { SetValue(CanUserReorderColumnsProperty, value); }
}
/// <summary>
/// Identifies the CanUserReorderColumns dependency property.
/// </summary>
public static readonly DependencyProperty CanUserReorderColumnsProperty =
DependencyProperty.Register(
"CanUserReorderColumns",
typeof(bool),
typeof(DataGrid),
new PropertyMetadata(DATAGRID_defaultCanUserReorderColumns));
/// <summary>
/// Gets or sets a value indicating whether the user can adjust column widths using the mouse.
/// </summary>
public bool CanUserResizeColumns
{
get { return (bool)GetValue(CanUserResizeColumnsProperty); }
set { SetValue(CanUserResizeColumnsProperty, value); }
}
/// <summary>
/// Identifies the CanUserResizeColumns dependency property.
/// </summary>
public static readonly DependencyProperty CanUserResizeColumnsProperty =
DependencyProperty.Register(
"CanUserResizeColumns",
typeof(bool),
typeof(DataGrid),
new PropertyMetadata(DATAGRID_defaultCanUserResizeColumns, OnCanUserResizeColumnsPropertyChanged));
/// <summary>
/// CanUserResizeColumns property changed handler.
/// </summary>
/// <param name="d">DataGrid that changed its CanUserResizeColumns.</param>
/// <param name="e">DependencyPropertyChangedEventArgs.</param>
private static void OnCanUserResizeColumnsPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
DataGrid dataGrid = d as DataGrid;
dataGrid.EnsureHorizontalLayout();
}
/// <summary>
/// Gets or sets a value indicating whether the user can sort columns by clicking the column header.
/// </summary>
public bool CanUserSortColumns
{
get { return (bool)GetValue(CanUserSortColumnsProperty); }
set { SetValue(CanUserSortColumnsProperty, value); }
}
/// <summary>
/// Identifies the CanUserSortColumns dependency property.
/// </summary>
public static readonly DependencyProperty CanUserSortColumnsProperty =
DependencyProperty.Register(
"CanUserSortColumns",
typeof(bool),
typeof(DataGrid),
new PropertyMetadata(DATAGRID_defaultCanUserSortColumns));
/// <summary>
/// Gets or sets the style that is used when rendering the data grid cells.
/// </summary>
public Style CellStyle
{
get { return GetValue(CellStyleProperty) as Style; }
set { SetValue(CellStyleProperty, value); }
}
/// <summary>
/// Identifies the <see cref="CellStyle"/> dependency property.
/// </summary>
public static readonly DependencyProperty CellStyleProperty =
DependencyProperty.Register(
"CellStyle",
typeof(Style),
typeof(DataGrid),
new PropertyMetadata(null, OnCellStylePropertyChanged));
private static void OnCellStylePropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
DataGrid dataGrid = d as DataGrid;
if (dataGrid != null)
{
Style previousStyle = e.OldValue as Style;
foreach (DataGridRow row in dataGrid.GetAllRows())
{
foreach (DataGridCell cell in row.Cells)
{
cell.EnsureStyle(previousStyle);
}
row.FillerCell.EnsureStyle(previousStyle);
}
dataGrid.InvalidateRowHeightEstimate();
}
}
/// <summary>
/// Gets or sets the property which determines how DataGrid content is copied to the Clipboard.
/// </summary>
public DataGridClipboardCopyMode ClipboardCopyMode
{
get { return (DataGridClipboardCopyMode)GetValue(ClipboardCopyModeProperty); }
set { SetValue(ClipboardCopyModeProperty, value); }
}
/// <summary>
/// Identifies the <see cref="ClipboardCopyMode"/> dependency property.
/// </summary>
public static readonly DependencyProperty ClipboardCopyModeProperty =
DependencyProperty.Register(
"ClipboardCopyMode",
typeof(DataGridClipboardCopyMode),
typeof(DataGrid),
new PropertyMetadata(DataGridClipboardCopyMode.ExcludeHeader));
/// <summary>
/// Gets or sets the height of the column headers row.
/// </summary>
public double ColumnHeaderHeight
{
get { return (double)GetValue(ColumnHeaderHeightProperty); }
set { SetValue(ColumnHeaderHeightProperty, value); }
}
/// <summary>
/// Identifies the ColumnHeaderHeight dependency property.
/// </summary>
public static readonly DependencyProperty ColumnHeaderHeightProperty =
DependencyProperty.Register(
"ColumnHeaderHeight",
typeof(double),
typeof(DataGrid),
new PropertyMetadata(double.NaN, OnColumnHeaderHeightPropertyChanged));
/// <summary>
/// ColumnHeaderHeightProperty property changed handler.
/// </summary>
/// <param name="d">DataGrid that changed its ColumnHeaderHeight.</param>
/// <param name="e">DependencyPropertyChangedEventArgs.</param>
private static void OnColumnHeaderHeightPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
DataGrid dataGrid = d as DataGrid;
if (!dataGrid.IsHandlerSuspended(e.Property))
{
double value = (double)e.NewValue;
if (value < DATAGRID_minimumColumnHeaderHeight)
{
dataGrid.SetValueNoCallback(e.Property, e.OldValue);
throw DataGridError.DataGrid.ValueMustBeGreaterThanOrEqualTo("value", "ColumnHeaderHeight", DATAGRID_minimumColumnHeaderHeight);
}
if (value > DATAGRID_maxHeadersThickness)
{
dataGrid.SetValueNoCallback(e.Property, e.OldValue);
throw DataGridError.DataGrid.ValueMustBeLessThanOrEqualTo("value", "ColumnHeaderHeight", DATAGRID_maxHeadersThickness);
}
dataGrid.InvalidateMeasure();
}
}
/// <summary>
/// Gets or sets the style that is used when rendering the column headers.
/// </summary>
public Style ColumnHeaderStyle
{
get { return GetValue(ColumnHeaderStyleProperty) as Style; }
set { SetValue(ColumnHeaderStyleProperty, value); }
}
/// <summary>
/// Identifies the ColumnHeaderStyle dependency property.
/// </summary>
public static readonly DependencyProperty ColumnHeaderStyleProperty =
DependencyProperty.Register(
"ColumnHeaderStyle",
typeof(Style),
typeof(DataGrid),
new PropertyMetadata(null, OnColumnHeaderStylePropertyChanged));
private static void OnColumnHeaderStylePropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
// TODO: ColumnHeaderStyle should be applied to the TopLeftCorner and the TopRightCorner as well
DataGrid dataGrid = d as DataGrid;
if (dataGrid != null)
{
Style previousStyle = e.OldValue as Style;
foreach (DataGridColumn column in dataGrid.Columns)
{
column.HeaderCell.EnsureStyle(previousStyle);
}
if (dataGrid.ColumnsInternal.FillerColumn != null)
{
dataGrid.ColumnsInternal.FillerColumn.HeaderCell.EnsureStyle(previousStyle);
}
}
}
/// <summary>
/// Gets or sets the standard width or automatic sizing mode of columns in the control.
/// </summary>
public DataGridLength ColumnWidth
{
get { return (DataGridLength)GetValue(ColumnWidthProperty); }
set { SetValue(ColumnWidthProperty, value); }
}
/// <summary>
/// Identifies the ColumnWidth dependency property.
/// </summary>
public static readonly DependencyProperty ColumnWidthProperty =
DependencyProperty.Register(
"ColumnWidth",
typeof(DataGridLength),
typeof(DataGrid),
new PropertyMetadata(DataGridLength.Auto, OnColumnWidthPropertyChanged));
/// <summary>
/// ColumnWidthProperty property changed handler.
/// </summary>
/// <param name="d">DataGrid that changed its ColumnWidth.</param>
/// <param name="e">DependencyPropertyChangedEventArgs.</param>
private static void OnColumnWidthPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
DataGrid dataGrid = d as DataGrid;
foreach (DataGridColumn column in dataGrid.ColumnsInternal.GetDisplayedColumns())
{
if (column.InheritsWidth)
{
column.SetWidthInternalNoCallback(dataGrid.ColumnWidth);
}
}
dataGrid.EnsureHorizontalLayout();
}
/// <summary>
/// Gets or sets the amount of data to fetch for virtualizing/prefetch operations.
/// </summary>
/// <returns>
/// The amount of data to fetch per interval, in pages.
/// </returns>
public double DataFetchSize
{
get { return (double)GetValue(DataFetchSizeProperty); }
set { SetValue(DataFetchSizeProperty, value); }
}
/// <summary>
/// Identifies the <see cref="DataFetchSize"/> dependency property
/// </summary>
public static readonly DependencyProperty DataFetchSizeProperty =
DependencyProperty.Register(
nameof(DataFetchSize),
typeof(double),
typeof(DataGrid),
new PropertyMetadata(DATAGRID_defaultDataFetchSize, OnDataFetchSizePropertyChanged));
/// <summary>
/// DataFetchSizeProperty property changed handler.
/// </summary>
/// <param name="d">DataGrid that changed its DataFetchSize.</param>
/// <param name="e">DependencyPropertyChangedEventArgs.</param>
private static void OnDataFetchSizePropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
DataGrid dataGrid = d as DataGrid;
if (!dataGrid.IsHandlerSuspended(e.Property))
{
double oldValue = (double)e.OldValue;
double newValue = (double)e.NewValue;
if (double.IsNaN(newValue))
{
dataGrid.SetValueNoCallback(e.Property, oldValue);
throw DataGridError.DataGrid.ValueCannotBeSetToNAN(nameof(dataGrid.DataFetchSize));
}
if (newValue < 0)
{
dataGrid.SetValueNoCallback(e.Property, oldValue);
throw DataGridError.DataGrid.ValueMustBeGreaterThanOrEqualTo("value", nameof(dataGrid.DataFetchSize), 0);
}
}
}
/// <summary>
/// Gets or sets the style that is used when rendering the drag indicator
/// that is displayed while dragging column headers.
/// </summary>
public Style DragIndicatorStyle
{
get { return GetValue(DragIndicatorStyleProperty) as Style; }
set { SetValue(DragIndicatorStyleProperty, value); }
}
/// <summary>
/// Identifies the <see cref="DragIndicatorStyle"/>
/// dependency property.
/// </summary>
public static readonly DependencyProperty DragIndicatorStyleProperty =
DependencyProperty.Register(
"DragIndicatorStyle",
typeof(Style),
typeof(DataGrid),
null);
/// <summary>
/// Gets or sets the style that is used when rendering the column headers.
/// </summary>
public Style DropLocationIndicatorStyle
{
get { return GetValue(DropLocationIndicatorStyleProperty) as Style; }
set { SetValue(DropLocationIndicatorStyleProperty, value); }
}
/// <summary>
/// Identifies the <see cref="DropLocationIndicatorStyle"/>
/// dependency property.
/// </summary>
public static readonly DependencyProperty DropLocationIndicatorStyleProperty =
DependencyProperty.Register(
"DropLocationIndicatorStyle",
typeof(Style),
typeof(DataGrid),
null);
/// <summary>
/// Gets or sets the number of columns that the user cannot scroll horizontally.
/// </summary>
public int FrozenColumnCount
{
get { return (int)GetValue(FrozenColumnCountProperty); }
set { SetValue(FrozenColumnCountProperty, value); }
}
/// <summary>
/// Identifies the <see cref="FrozenColumnCount"/>
/// dependency property.
/// </summary>
public static readonly DependencyProperty FrozenColumnCountProperty =
DependencyProperty.Register(
"FrozenColumnCount",
typeof(int),
typeof(DataGrid),
new PropertyMetadata(0, OnFrozenColumnCountPropertyChanged));
private static void OnFrozenColumnCountPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
DataGrid dataGrid = d as DataGrid;
if (!dataGrid.IsHandlerSuspended(e.Property))
{
if ((int)e.NewValue < 0)
{