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 pathDataGridColumns.cs
More file actions
1924 lines (1680 loc) · 88.2 KB
/
DataGridColumns.cs
File metadata and controls
1924 lines (1680 loc) · 88.2 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.ComponentModel.DataAnnotations;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using Microsoft.Toolkit.Uwp.UI.Controls.DataGridInternals;
using Microsoft.Toolkit.Uwp.UI.Utilities;
using Microsoft.Toolkit.Uwp.Utilities;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
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
{
/// <summary>
/// OnColumnDisplayIndexChanged
/// </summary>
/// <param name="e">Event arguments.</param>
protected virtual void OnColumnDisplayIndexChanged(DataGridColumnEventArgs e)
{
this.ColumnDisplayIndexChanged?.Invoke(this, e);
}
/// <summary>
/// OnColumnReordered
/// </summary>
/// <param name="e">Event arguments.</param>
protected internal virtual void OnColumnReordered(DataGridColumnEventArgs e)
{
this.EnsureVerticalGridLines();
this.ColumnReordered?.Invoke(this, e);
}
/// <summary>
/// OnColumnReordering
/// </summary>
/// <param name="e">Event arguments.</param>
protected internal virtual void OnColumnReordering(DataGridColumnReorderingEventArgs e)
{
this.ColumnReordering?.Invoke(this, e);
}
/// <summary>
/// OnColumnSorting
/// </summary>
/// <param name="e">Event arguments.</param>
protected internal virtual void OnColumnSorting(DataGridColumnEventArgs e)
{
this.Sorting?.Invoke(this, e);
}
// Returns the column's width
internal static double GetEdgedColumnWidth(DataGridColumn dataGridColumn)
{
DiagnosticsDebug.Assert(dataGridColumn != null, "Expected non-null dataGridColumn.");
return dataGridColumn.ActualWidth;
}
/// <summary>
/// Adjusts the widths of all columns with DisplayIndex >= displayIndex such that the total
/// width is adjusted by the given amount, if possible. If the total desired adjustment amount
/// could not be met, the remaining amount of adjustment is returned.
/// </summary>
/// <param name="displayIndex">Starting column DisplayIndex.</param>
/// <param name="amount">Adjustment amount (positive for increase, negative for decrease).</param>
/// <param name="userInitiated">Whether or not this adjustment was initiated by a user action.</param>
/// <returns>The remaining amount of adjustment.</returns>
internal double AdjustColumnWidths(int displayIndex, double amount, bool userInitiated)
{
if (!DoubleUtil.IsZero(amount))
{
if (amount < 0)
{
amount = DecreaseColumnWidths(displayIndex, amount, userInitiated);
}
else
{
amount = IncreaseColumnWidths(displayIndex, amount, userInitiated);
}
}
return amount;
}
/// <summary>
/// Grows an auto-column's width to the desired width.
/// </summary>
/// <param name="column">Auto-column to adjust.</param>
/// <param name="desiredWidth">The new desired width of the column.</param>
internal void AutoSizeColumn(DataGridColumn column, double desiredWidth)
{
DiagnosticsDebug.Assert(
column.Width.IsAuto || column.Width.IsSizeToCells || column.Width.IsSizeToHeader || (!this.UsesStarSizing && column.Width.IsStar),
"Expected column.Width.IsAuto or column.Width.IsSizeToCells or column.Width.IsSizeToHeader or (!UsesStarSizing && column.Width.IsStar).");
// If we're using star sizing and this is the first time we've measured this particular auto-column,
// we want to allow all rows to get measured before we setup the star widths. We won't know the final
// desired value of the column until all rows have been measured. Because of this, we wait until
// an Arrange occurs before we adjust star widths.
if (this.UsesStarSizing && !column.IsInitialDesiredWidthDetermined)
{
this.AutoSizingColumns = true;
}
// Update the column's DesiredValue if it needs to grow to fit the new desired value
if (desiredWidth > column.Width.DesiredValue || double.IsNaN(column.Width.DesiredValue))
{
// If this auto-growth occurs after the column's initial desired width has been determined,
// then the growth should act like a resize (squish columns to the right). Otherwise, if
// this column is newly added, we'll just set its display value directly.
if (this.UsesStarSizing && column.IsInitialDesiredWidthDetermined)
{
column.Resize(column.Width.Value, column.Width.UnitType, desiredWidth, desiredWidth, false);
}
else
{
column.SetWidthInternalNoCallback(new DataGridLength(column.Width.Value, column.Width.UnitType, desiredWidth, desiredWidth));
this.OnColumnWidthChanged(column);
}
}
}
internal bool ColumnRequiresRightGridLine(DataGridColumn dataGridColumn, bool includeLastRightGridLineWhenPresent)
{
return (this.GridLinesVisibility == DataGridGridLinesVisibility.Vertical || this.GridLinesVisibility == DataGridGridLinesVisibility.All) && this.VerticalGridLinesBrush != null &&
(dataGridColumn != this.ColumnsInternal.LastVisibleColumn || (includeLastRightGridLineWhenPresent && this.ColumnsInternal.FillerColumn.IsActive));
}
internal DataGridColumnCollection CreateColumnsInstance()
{
return new DataGridColumnCollection(this);
}
/// <summary>
/// Decreases the widths of all columns with DisplayIndex >= displayIndex such that the total
/// width is decreased by the given amount, if possible. If the total desired adjustment amount
/// could not be met, the remaining amount of adjustment is returned.
/// </summary>
/// <param name="displayIndex">Starting column DisplayIndex.</param>
/// <param name="amount">Amount to decrease (in pixels).</param>
/// <param name="userInitiated">Whether or not this adjustment was initiated by a user action.</param>
/// <returns>The remaining amount of adjustment.</returns>
internal double DecreaseColumnWidths(int displayIndex, double amount, bool userInitiated)
{
// 1. Take space from non-star columns with widths larger than desired widths (left to right).
amount = DecreaseNonStarColumnWidths(displayIndex, c => c.Width.DesiredValue, amount, false, false);
// 2. Take space from star columns until they reach their min.
amount = AdjustStarColumnWidths(displayIndex, amount, userInitiated);
// 3. Take space from non-star columns that have already been initialized, until they reach their min (right to left).
amount = DecreaseNonStarColumnWidths(displayIndex, c => c.ActualMinWidth, amount, true, false);
// 4. Take space from all non-star columns until they reach their min, even if they are new (right to left).
amount = DecreaseNonStarColumnWidths(displayIndex, c => c.ActualMinWidth, amount, true, true);
return amount;
}
internal bool GetColumnReadOnlyState(DataGridColumn dataGridColumn, bool isReadOnly)
{
DiagnosticsDebug.Assert(dataGridColumn != null, "Expected non-null dataGridColumn.");
DataGridBoundColumn dataGridBoundColumn = dataGridColumn as DataGridBoundColumn;
if (dataGridBoundColumn != null && dataGridBoundColumn.Binding != null)
{
string path = null;
if (dataGridBoundColumn.Binding.Path != null)
{
path = dataGridBoundColumn.Binding.Path.Path;
}
if (!string.IsNullOrEmpty(path))
{
return this.DataConnection.GetPropertyIsReadOnly(path) || isReadOnly;
}
}
return isReadOnly;
}
/// <summary>
/// Increases the widths of all columns with DisplayIndex >= displayIndex such that the total
/// width is increased by the given amount, if possible. If the total desired adjustment amount
/// could not be met, the remaining amount of adjustment is returned.
/// </summary>
/// <param name="displayIndex">Starting column DisplayIndex.</param>
/// <param name="amount">Amount of increase (in pixels).</param>
/// <param name="userInitiated">Whether or not this adjustment was initiated by a user action.</param>
/// <returns>The remaining amount of adjustment.</returns>
internal double IncreaseColumnWidths(int displayIndex, double amount, bool userInitiated)
{
// 1. Give space to non-star columns that are smaller than their desired widths (left to right).
amount = IncreaseNonStarColumnWidths(displayIndex, c => c.Width.DesiredValue, amount, false, false);
// 2. Give space to star columns until they reach their max.
amount = AdjustStarColumnWidths(displayIndex, amount, userInitiated);
// 3. Give space to non-star columns that have already been initialized, until they reach their max (right to left).
amount = IncreaseNonStarColumnWidths(displayIndex, c => c.ActualMaxWidth, amount, true, false);
// 4. Give space to all non-star columns until they reach their max, even if they are new (right to left).
amount = IncreaseNonStarColumnWidths(displayIndex, c => c.ActualMaxWidth, amount, true, false);
return amount;
}
internal void OnClearingColumns()
{
// Rows need to be cleared first. There cannot be rows without also having columns.
ClearRows(false);
// Removing all the column header cells
RemoveDisplayedColumnHeaders();
_horizontalOffset = _negHorizontalOffset = 0;
if (_hScrollBar != null && _hScrollBar.Visibility == Visibility.Visible)
{
_hScrollBar.Value = 0;
}
}
/// <summary>
/// Invalidates the widths of all columns because the resizing behavior of an individual column has changed.
/// </summary>
/// <param name="column">Column with CanUserResize property that has changed.</param>
internal void OnColumnCanUserResizeChanged(DataGridColumn column)
{
if (column.IsVisible)
{
EnsureHorizontalLayout();
}
}
internal void OnColumnCellStyleChanged(DataGridColumn column, Style previousStyle)
{
// Set HeaderCell.Style for displayed rows if HeaderCell.Style is not already set
foreach (DataGridRow row in GetAllRows())
{
row.Cells[column.Index].EnsureStyle(previousStyle);
}
InvalidateRowHeightEstimate();
}
internal void OnColumnCollectionChanged_PostNotification(bool columnsGrew)
{
if (columnsGrew &&
this.CurrentColumnIndex == -1)
{
MakeFirstDisplayedCellCurrentCell();
}
if (_autoGeneratingColumnOperationCount == 0)
{
EnsureRowsPresenterVisibility();
InvalidateRowHeightEstimate();
}
}
internal void OnColumnCollectionChanged_PreNotification(bool columnsGrew)
{
// dataGridColumn==null means the collection was refreshed.
if (columnsGrew && _autoGeneratingColumnOperationCount == 0 && this.ColumnsItemsInternal.Count == 1)
{
RefreshRows(false /*recycleRows*/, true /*clearRows*/);
}
else
{
InvalidateMeasure();
}
}
internal void OnColumnDisplayIndexChanged(DataGridColumn dataGridColumn)
{
DiagnosticsDebug.Assert(dataGridColumn != null, "Expected non-null dataGridColumn.");
DataGridColumnEventArgs e = new DataGridColumnEventArgs(dataGridColumn);
// Call protected method to raise event
if (dataGridColumn != this.ColumnsInternal.RowGroupSpacerColumn)
{
OnColumnDisplayIndexChanged(e);
}
}
internal void OnColumnDisplayIndexChanged_PostNotification()
{
// Notifications for adjusted display indexes.
FlushDisplayIndexChanged(true /*raiseEvent*/);
// Our displayed columns may have changed so recompute them
UpdateDisplayedColumns();
// Invalidate layout
CorrectColumnFrozenStates();
EnsureHorizontalLayout();
}
internal void OnColumnDisplayIndexChanging(DataGridColumn targetColumn, int newDisplayIndex)
{
DiagnosticsDebug.Assert(targetColumn != null, "Expected non-null targetColumn.");
DiagnosticsDebug.Assert(newDisplayIndex != targetColumn.DisplayIndexWithFiller, "Expected newDisplayIndex other than targetColumn.DisplayIndexWithFiller.");
if (InDisplayIndexAdjustments)
{
// We are within columns display indexes adjustments. We do not allow changing display indexes while adjusting them.
throw DataGridError.DataGrid.CannotChangeColumnCollectionWhileAdjustingDisplayIndexes();
}
try
{
InDisplayIndexAdjustments = true;
bool trackChange = targetColumn != this.ColumnsInternal.RowGroupSpacerColumn;
DataGridColumn column;
// Move is legal - let's adjust the affected display indexes.
if (newDisplayIndex < targetColumn.DisplayIndexWithFiller)
{
// DisplayIndex decreases. All columns with newDisplayIndex <= DisplayIndex < targetColumn.DisplayIndex
// get their DisplayIndex incremented.
for (int i = newDisplayIndex; i < targetColumn.DisplayIndexWithFiller; i++)
{
column = this.ColumnsInternal.GetColumnAtDisplayIndex(i);
column.DisplayIndexWithFiller = column.DisplayIndexWithFiller + 1;
if (trackChange)
{
column.DisplayIndexHasChanged = true; // OnColumnDisplayIndexChanged needs to be raised later on
}
}
}
else
{
// DisplayIndex increases. All columns with targetColumn.DisplayIndex < DisplayIndex <= newDisplayIndex
// get their DisplayIndex decremented.
for (int i = newDisplayIndex; i > targetColumn.DisplayIndexWithFiller; i--)
{
column = this.ColumnsInternal.GetColumnAtDisplayIndex(i);
column.DisplayIndexWithFiller = column.DisplayIndexWithFiller - 1;
if (trackChange)
{
column.DisplayIndexHasChanged = true; // OnColumnDisplayIndexChanged needs to be raised later on
}
}
}
// Now let's actually change the order of the DisplayIndexMap
if (targetColumn.DisplayIndexWithFiller != -1)
{
this.ColumnsInternal.DisplayIndexMap.Remove(targetColumn.Index);
}
this.ColumnsInternal.DisplayIndexMap.Insert(newDisplayIndex, targetColumn.Index);
}
finally
{
InDisplayIndexAdjustments = false;
}
// Note that displayIndex of moved column is updated by caller.
}
internal void OnColumnBindingChanged(DataGridBoundColumn column)
{
// Update Binding in Displayed rows by regenerating the affected elements
if (_rowsPresenter != null)
{
foreach (DataGridRow row in GetAllRows())
{
PopulateCellContent(false /*isCellEdited*/, column, row, row.Cells[column.Index]);
}
}
}
internal void OnColumnElementStyleChanged(DataGridBoundColumn column)
{
// Update Element Style in Displayed rows
foreach (DataGridRow row in GetAllRows())
{
FrameworkElement element = column.GetCellContent(row);
if (element != null)
{
element.SetStyleWithType(column.ElementStyle);
}
}
InvalidateRowHeightEstimate();
}
internal void OnColumnHeaderDragStarted(DragStartedEventArgs e)
{
if (this.ColumnHeaderDragStarted != null)
{
this.ColumnHeaderDragStarted(this, e);
}
}
internal void OnColumnHeaderDragDelta(DragDeltaEventArgs e)
{
if (this.ColumnHeaderDragDelta != null)
{
this.ColumnHeaderDragDelta(this, e);
}
}
internal void OnColumnHeaderDragCompleted(DragCompletedEventArgs e)
{
if (this.ColumnHeaderDragCompleted != null)
{
this.ColumnHeaderDragCompleted(this, e);
}
}
/// <summary>
/// Adjusts the specified column's width according to its new maximum value.
/// </summary>
/// <param name="column">The column to adjust.</param>
/// <param name="oldValue">The old ActualMaxWidth of the column.</param>
internal void OnColumnMaxWidthChanged(DataGridColumn column, double oldValue)
{
DiagnosticsDebug.Assert(column != null, "Expected non-null column.");
if (column.Visibility == Visibility.Visible && oldValue != column.ActualMaxWidth)
{
if (column.ActualMaxWidth < column.Width.DisplayValue)
{
// If the maximum width has caused the column to decrease in size, try first to resize
// the columns to the right to make up for the difference in width, but don't limit the column's
// final display value to how much they could be resized.
AdjustColumnWidths(column.DisplayIndex + 1, column.Width.DisplayValue - column.ActualMaxWidth, false);
column.SetWidthDisplayValue(column.ActualMaxWidth);
}
else if (column.Width.DisplayValue == oldValue && column.Width.DesiredValue > column.Width.DisplayValue)
{
// If the column was previously limited by its maximum value but has more room now,
// attempt to resize the column to its desired width.
column.Resize(column.Width.Value, column.Width.UnitType, column.Width.DesiredValue, column.Width.DesiredValue, false);
}
OnColumnWidthChanged(column);
}
}
/// <summary>
/// Adjusts the specified column's width according to its new minimum value.
/// </summary>
/// <param name="column">The column to adjust.</param>
/// <param name="oldValue">The old ActualMinWidth of the column.</param>
internal void OnColumnMinWidthChanged(DataGridColumn column, double oldValue)
{
DiagnosticsDebug.Assert(column != null, "Expected non-null column.");
if (column.Visibility == Visibility.Visible && oldValue != column.ActualMinWidth)
{
if (column.ActualMinWidth > column.Width.DisplayValue)
{
// If the minimum width has caused the column to increase in size, try first to resize
// the columns to the right to make up for the difference in width, but don't limit the column's
// final display value to how much they could be resized.
AdjustColumnWidths(column.DisplayIndex + 1, column.Width.DisplayValue - column.ActualMinWidth, false);
column.SetWidthDisplayValue(column.ActualMinWidth);
}
else if (column.Width.DisplayValue == oldValue && column.Width.DesiredValue < column.Width.DisplayValue)
{
// If the column was previously limited by its minimum value but can be smaller now,
// attempt to resize the column to its desired width.
column.Resize(column.Width.Value, column.Width.UnitType, column.Width.DesiredValue, column.Width.DesiredValue, false);
}
OnColumnWidthChanged(column);
}
}
internal void OnColumnReadOnlyStateChanging(DataGridColumn dataGridColumn, bool isReadOnly)
{
DiagnosticsDebug.Assert(dataGridColumn != null, "Expected non-null dataGridColumn.");
if (isReadOnly && this.CurrentColumnIndex == dataGridColumn.Index)
{
// Edited column becomes read-only. Exit editing mode.
if (!EndCellEdit(DataGridEditAction.Commit, true /*exitEditingMode*/, this.ContainsFocus /*keepFocus*/, true /*raiseEvents*/))
{
EndCellEdit(DataGridEditAction.Cancel, true /*exitEditingMode*/, this.ContainsFocus /*keepFocus*/, false /*raiseEvents*/);
}
}
}
internal void OnColumnVisibleStateChanged(DataGridColumn updatedColumn)
{
DiagnosticsDebug.Assert(updatedColumn != null, "Expected non-null updatedColumn.");
CorrectColumnFrozenStates();
UpdateDisplayedColumns();
EnsureRowsPresenterVisibility();
EnsureHorizontalLayout();
InvalidateColumnHeadersMeasure();
if (updatedColumn.IsVisible &&
this.ColumnsInternal.VisibleColumnCount == 1 && this.CurrentColumnIndex == -1)
{
DiagnosticsDebug.Assert(this.SelectedIndex == this.DataConnection.IndexOf(this.SelectedItem), "Expected SelectedIndex equals DataConnection.IndexOf(this.SelectedItem).");
if (this.SelectedIndex != -1)
{
SetAndSelectCurrentCell(updatedColumn.Index, this.SelectedIndex, true /*forceCurrentCellSelection*/);
}
else
{
MakeFirstDisplayedCellCurrentCell();
}
}
// We need to explicitly collapse the cells of the invisible column because layout only goes through
// visible ones
if (updatedColumn.Visibility == Visibility.Collapsed)
{
foreach (DataGridRow row in GetAllRows())
{
row.Cells[updatedColumn.Index].Visibility = Visibility.Collapsed;
}
}
}
internal void OnColumnVisibleStateChanging(DataGridColumn targetColumn)
{
DiagnosticsDebug.Assert(targetColumn != null, "Expected non-null targetColumn.");
if (targetColumn.IsVisible && this.CurrentColumn == targetColumn)
{
// Column of the current cell is made invisible. Trying to move the current cell to a neighbor column. May throw an exception.
DataGridColumn dataGridColumn = this.ColumnsInternal.GetNextVisibleColumn(targetColumn);
if (dataGridColumn == null)
{
dataGridColumn = this.ColumnsInternal.GetPreviousVisibleNonFillerColumn(targetColumn);
}
if (dataGridColumn == null)
{
SetCurrentCellCore(-1, -1);
}
else
{
SetCurrentCellCore(dataGridColumn.Index, this.CurrentSlot);
}
}
}
internal void OnColumnWidthChanged(DataGridColumn updatedColumn)
{
DiagnosticsDebug.Assert(updatedColumn != null, "Expected non-null updatedColumn.");
if (updatedColumn.IsVisible)
{
EnsureHorizontalLayout();
}
}
internal void OnFillerColumnWidthNeeded(double finalWidth)
{
DataGridFillerColumn fillerColumn = this.ColumnsInternal.FillerColumn;
double totalColumnsWidth = this.ColumnsInternal.VisibleEdgedColumnsWidth;
if (finalWidth - totalColumnsWidth > DATAGRID_roundingDelta)
{
fillerColumn.FillerWidth = finalWidth - totalColumnsWidth;
}
else
{
fillerColumn.FillerWidth = 0;
}
}
internal void OnInsertedColumn_PostNotification(DataGridCellCoordinates newCurrentCellCoordinates, int newDisplayIndex)
{
// Update current cell if needed
if (newCurrentCellCoordinates.ColumnIndex != -1)
{
DiagnosticsDebug.Assert(this.CurrentColumnIndex == -1, "Expected CurrentColumnIndex equals -1.");
SetAndSelectCurrentCell(
newCurrentCellCoordinates.ColumnIndex,
newCurrentCellCoordinates.Slot,
this.ColumnsInternal.VisibleColumnCount == 1 /*forceCurrentCellSelection*/);
if (newDisplayIndex < this.FrozenColumnCountWithFiller)
{
CorrectColumnFrozenStates();
}
}
}
internal void OnInsertedColumn_PreNotification(DataGridColumn insertedColumn)
{
// Fix the Index of all following columns
CorrectColumnIndexesAfterInsertion(insertedColumn, 1);
DiagnosticsDebug.Assert(insertedColumn.Index >= 0, "Expected positive insertedColumn.Index.");
DiagnosticsDebug.Assert(insertedColumn.Index < this.ColumnsItemsInternal.Count, "insertedColumn.Index smaller than ColumnsItemsInternal.Count.");
DiagnosticsDebug.Assert(insertedColumn.OwningGrid == this, "Expected insertedColumn.OwningGrid equals this DataGrid.");
CorrectColumnDisplayIndexesAfterInsertion(insertedColumn);
InsertDisplayedColumnHeader(insertedColumn);
// Insert the missing data cells
if (this.SlotCount > 0)
{
int newColumnCount = this.ColumnsItemsInternal.Count;
foreach (DataGridRow row in GetAllRows())
{
if (row.Cells.Count < newColumnCount)
{
AddNewCellPrivate(row, insertedColumn);
}
}
}
if (insertedColumn.IsVisible)
{
EnsureHorizontalLayout();
}
DataGridBoundColumn boundColumn = insertedColumn as DataGridBoundColumn;
if (boundColumn != null && !boundColumn.IsAutoGenerated)
{
boundColumn.SetHeaderFromBinding();
}
}
internal DataGridCellCoordinates OnInsertingColumn(int columnIndexInserted, DataGridColumn insertColumn)
{
DataGridCellCoordinates newCurrentCellCoordinates;
DiagnosticsDebug.Assert(insertColumn != null, "Expected non-null insertColumn.");
if (insertColumn.OwningGrid != null && insertColumn != this.ColumnsInternal.RowGroupSpacerColumn)
{
throw DataGridError.DataGrid.ColumnCannotBeReassignedToDifferentDataGrid();
}
// Reset current cell if there is one, no matter the relative position of the columns involved
if (this.CurrentColumnIndex != -1)
{
_temporarilyResetCurrentCell = true;
newCurrentCellCoordinates = new DataGridCellCoordinates(
columnIndexInserted <= this.CurrentColumnIndex ? this.CurrentColumnIndex + 1 : this.CurrentColumnIndex,
this.CurrentSlot);
ResetCurrentCellCore();
}
else
{
newCurrentCellCoordinates = new DataGridCellCoordinates(-1, -1);
}
return newCurrentCellCoordinates;
}
internal void OnRemovedColumn_PostNotification(DataGridCellCoordinates newCurrentCellCoordinates)
{
// Update current cell if needed
if (newCurrentCellCoordinates.ColumnIndex != -1)
{
DiagnosticsDebug.Assert(this.CurrentColumnIndex == -1, "Expected CurrentColumnIndex equals -1.");
SetAndSelectCurrentCell(newCurrentCellCoordinates.ColumnIndex, newCurrentCellCoordinates.Slot, false /*forceCurrentCellSelection*/);
}
}
internal void OnRemovedColumn_PreNotification(DataGridColumn removedColumn)
{
DiagnosticsDebug.Assert(removedColumn.Index >= 0, "Expected positive removedColumn.Index.");
DiagnosticsDebug.Assert(removedColumn.OwningGrid == null, "Expected null removedColumn.OwningGrid.");
// Intentionally keep the DisplayIndex intact after detaching the column.
CorrectColumnIndexesAfterDeletion(removedColumn);
CorrectColumnDisplayIndexesAfterDeletion(removedColumn);
// If the detached column was frozen, a new column needs to take its place
if (removedColumn.IsFrozen)
{
removedColumn.IsFrozen = false;
CorrectColumnFrozenStates();
}
UpdateDisplayedColumns();
// Fix the existing rows by removing cells at correct index
int newColumnCount = this.ColumnsItemsInternal.Count;
if (_rowsPresenter != null)
{
foreach (DataGridRow row in GetAllRows())
{
if (row.Cells.Count > newColumnCount)
{
row.Cells.RemoveAt(removedColumn.Index);
}
}
_rowsPresenter.InvalidateArrange();
}
RemoveDisplayedColumnHeader(removedColumn);
}
internal DataGridCellCoordinates OnRemovingColumn(DataGridColumn dataGridColumn)
{
DiagnosticsDebug.Assert(dataGridColumn != null, "Expected non-null dataGridColumn.");
DiagnosticsDebug.Assert(dataGridColumn.Index >= 0, "Expected positive dataGridColumn.Index.");
DiagnosticsDebug.Assert(dataGridColumn.Index < this.ColumnsItemsInternal.Count, "Expected dataGridColumn.Index smaller than ColumnsItemsInternal.Count.");
DataGridCellCoordinates newCurrentCellCoordinates;
_temporarilyResetCurrentCell = false;
int columnIndex = dataGridColumn.Index;
// Reset the current cell's address if there is one.
if (this.CurrentColumnIndex != -1)
{
int newCurrentColumnIndex = this.CurrentColumnIndex;
if (columnIndex == newCurrentColumnIndex)
{
DataGridColumn dataGridColumnNext = this.ColumnsInternal.GetNextVisibleColumn(this.ColumnsItemsInternal[columnIndex]);
if (dataGridColumnNext != null)
{
if (dataGridColumnNext.Index > columnIndex)
{
newCurrentColumnIndex = dataGridColumnNext.Index - 1;
}
else
{
newCurrentColumnIndex = dataGridColumnNext.Index;
}
}
else
{
DataGridColumn dataGridColumnPrevious = this.ColumnsInternal.GetPreviousVisibleNonFillerColumn(this.ColumnsItemsInternal[columnIndex]);
if (dataGridColumnPrevious != null)
{
if (dataGridColumnPrevious.Index > columnIndex)
{
newCurrentColumnIndex = dataGridColumnPrevious.Index - 1;
}
else
{
newCurrentColumnIndex = dataGridColumnPrevious.Index;
}
}
else
{
newCurrentColumnIndex = -1;
}
}
}
else if (columnIndex < newCurrentColumnIndex)
{
newCurrentColumnIndex--;
}
newCurrentCellCoordinates = new DataGridCellCoordinates(newCurrentColumnIndex, (newCurrentColumnIndex == -1) ? -1 : this.CurrentSlot);
if (columnIndex == this.CurrentColumnIndex)
{
// If the commit fails, force a cancel edit
if (!this.CommitEdit(DataGridEditingUnit.Row, false /*exitEditingMode*/))
{
this.CancelEdit(DataGridEditingUnit.Row, false /*raiseEvents*/);
}
}
else
{
// Underlying data of deleted column is gone. It cannot be accessed anymore.
// Do not end editing mode so that CellValidation doesn't get raised, since that event needs the current formatted value.
_temporarilyResetCurrentCell = true;
}
bool success = this.SetCurrentCellCore(-1, -1);
DiagnosticsDebug.Assert(success, "Expected successful call to SetCurrentCellCore.");
}
else
{
newCurrentCellCoordinates = new DataGridCellCoordinates(-1, -1);
}
// If the last column is removed, delete all the rows first.
if (this.ColumnsItemsInternal.Count == 1)
{
ClearRows(false);
}
// Is deleted column scrolled off screen?
if (dataGridColumn.IsVisible &&
!dataGridColumn.IsFrozen &&
this.DisplayData.FirstDisplayedScrollingCol >= 0)
{
// Deleted column is part of scrolling columns.
if (this.DisplayData.FirstDisplayedScrollingCol == dataGridColumn.Index)
{
// Deleted column is first scrolling column
_horizontalOffset -= _negHorizontalOffset;
_negHorizontalOffset = 0;
}
else if (!this.ColumnsInternal.DisplayInOrder(this.DisplayData.FirstDisplayedScrollingCol, dataGridColumn.Index))
{
// Deleted column is displayed before first scrolling column
DiagnosticsDebug.Assert(_horizontalOffset >= GetEdgedColumnWidth(dataGridColumn), "Expected _horizontalOffset greater than or equal to GetEdgedColumnWidth(dataGridColumn).");
_horizontalOffset -= GetEdgedColumnWidth(dataGridColumn);
}
if (_hScrollBar != null && _hScrollBar.Visibility == Visibility.Visible)
{
_hScrollBar.Value = _horizontalOffset;
}
}
return newCurrentCellCoordinates;
}
/// <summary>
/// Called when a column property changes, and its cells need to adjust that column change.
/// </summary>
internal void RefreshColumnElements(DataGridColumn dataGridColumn, string propertyName)
{
DiagnosticsDebug.Assert(dataGridColumn != null, "Expected non-null dataGridColumn.");
// Take care of the non-displayed loaded rows
for (int index = 0; index < _loadedRows.Count;)
{
DataGridRow dataGridRow = _loadedRows[index];
DiagnosticsDebug.Assert(dataGridRow != null, "Expected non-null dataGridRow.");
if (!this.IsSlotVisible(dataGridRow.Slot))
{
RefreshCellElement(dataGridColumn, dataGridRow, propertyName);
}
index++;
}
// Take care of the displayed rows
if (_rowsPresenter != null)
{
foreach (DataGridRow row in GetAllRows())
{
RefreshCellElement(dataGridColumn, row, propertyName);
}
// This update could change layout so we need to update our estimate and invalidate
InvalidateRowHeightEstimate();
InvalidateMeasure();
}
}
/// <summary>
/// Decreases the width of a non-star column by the given amount, if possible. If the total desired
/// adjustment amount could not be met, the remaining amount of adjustment is returned. The adjustment
/// stops when the column's target width has been met.
/// </summary>
/// <param name="column">Column to adjust.</param>
/// <param name="targetWidth">The target width of the column (in pixels).</param>
/// <param name="amount">Amount to decrease (in pixels).</param>
/// <returns>The remaining amount of adjustment.</returns>
private static double DecreaseNonStarColumnWidth(DataGridColumn column, double targetWidth, double amount)
{
DiagnosticsDebug.Assert(amount < 0, "Expected negative amount.");
DiagnosticsDebug.Assert(column.Width.UnitType != DataGridLengthUnitType.Star, "column.Width.UnitType other than DataGridLengthUnitType.Star.");
if (DoubleUtil.GreaterThanOrClose(targetWidth, column.Width.DisplayValue))
{
return amount;
}
double adjustment = Math.Max(
column.ActualMinWidth - column.Width.DisplayValue,
Math.Max(targetWidth - column.Width.DisplayValue, amount));
column.SetWidthDisplayValue(column.Width.DisplayValue + adjustment);
return amount - adjustment;
}
private static DataGridAutoGeneratingColumnEventArgs GenerateColumn(Type propertyType, string propertyName, string header)
{
// Create a new DataBoundColumn for the Property
DataGridBoundColumn newColumn = GetDataGridColumnFromType(propertyType);
Binding binding = new Binding();
binding.Path = new PropertyPath(propertyName);
newColumn.Binding = binding;
newColumn.Header = header;
newColumn.IsAutoGenerated = true;
return new DataGridAutoGeneratingColumnEventArgs(propertyName, propertyType, newColumn);
}
private static DataGridBoundColumn GetDataGridColumnFromType(Type type)
{
DiagnosticsDebug.Assert(type != null, "Expected non-null type.");
if (type == typeof(bool))
{
return new DataGridCheckBoxColumn();
}
else if (type == typeof(bool?))
{
DataGridCheckBoxColumn column = new DataGridCheckBoxColumn();
column.IsThreeState = true;
return column;
}
return new DataGridTextColumn();
}
/// <summary>
/// Increases the width of a non-star column by the given amount, if possible. If the total desired
/// adjustment amount could not be met, the remaining amount of adjustment is returned. The adjustment
/// stops when the column's target width has been met.
/// </summary>
/// <param name="column">Column to adjust.</param>
/// <param name="targetWidth">The target width of the column (in pixels).</param>
/// <param name="amount">Amount to increase (in pixels).</param>
/// <returns>The remaining amount of adjustment.</returns>
private static double IncreaseNonStarColumnWidth(DataGridColumn column, double targetWidth, double amount)
{
DiagnosticsDebug.Assert(amount > 0, "Expected strictly positive amount.");
DiagnosticsDebug.Assert(column.Width.UnitType != DataGridLengthUnitType.Star, "Expected column.Width.UnitType other than DataGridLengthUnitType.Star.");
if (targetWidth <= column.Width.DisplayValue)
{
return amount;
}
double adjustment = Math.Min(
column.ActualMaxWidth - column.Width.DisplayValue,
Math.Min(targetWidth - column.Width.DisplayValue, amount));
column.SetWidthDisplayValue(column.Width.DisplayValue + adjustment);
return amount - adjustment;
}
private static void RefreshCellElement(DataGridColumn dataGridColumn, DataGridRow dataGridRow, string propertyName)
{
DiagnosticsDebug.Assert(dataGridColumn != null, "Expected non-null dataGridColumn.");
DiagnosticsDebug.Assert(dataGridRow != null, "Expected non-null dataGridRow.");
DataGridCell dataGridCell = dataGridRow.Cells[dataGridColumn.Index];
DiagnosticsDebug.Assert(dataGridCell != null, "Expected non-null dataGridCell.");
FrameworkElement element = dataGridCell.Content as FrameworkElement;
if (element != null)
{
dataGridColumn.RefreshCellContent(element, dataGridRow.ComputedForeground, propertyName);
}
}
private bool AddGeneratedColumn(DataGridAutoGeneratingColumnEventArgs e)
{
// Raise the AutoGeneratingColumn event in case the user wants to Cancel or Replace the
// column being generated
OnAutoGeneratingColumn(e);
if (e.Cancel)
{
return false;
}
else
{
if (e.Column != null)
{
// Set the IsAutoGenerated flag here in case the user provides a custom auto-generated column
e.Column.IsAutoGenerated = true;
}
this.ColumnsInternal.Add(e.Column);
this.ColumnsInternal.AutogeneratedColumnCount++;
return true;
}
}
/// <summary>
/// Adjusts the widths of all star columns with DisplayIndex >= displayIndex such that the total
/// width is adjusted by the given amount, if possible. If the total desired adjustment amount
/// could not be met, the remaining amount of adjustment is returned.
/// </summary>
/// <param name="displayIndex">Starting column DisplayIndex.</param>
/// <param name="adjustment">Adjustment amount (positive for increase, negative for decrease).</param>
/// <param name="userInitiated">Whether or not this adjustment was initiated by a user action.</param>
/// <returns>The remaining amount of adjustment.</returns>
private double AdjustStarColumnWidths(int displayIndex, double adjustment, bool userInitiated)
{
double remainingAdjustment = adjustment;
if (DoubleUtil.IsZero(remainingAdjustment))
{
return remainingAdjustment;
}
bool increase = remainingAdjustment > 0;
// Make an initial pass through the star columns to total up some values.