Repository navigation
Expand file tree
/
Copy pathTableViewer.xaml.cs
More file actions
4885 lines (4413 loc) · 219 KB
/
Copy pathTableViewer.xaml.cs
File metadata and controls
4885 lines (4413 loc) · 219 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 System;
using System.Collections.Generic;
using System.Data;
using System.Globalization;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using DatabaseManager;
using Microsoft.Win32;
namespace DatabaseControls
{
/// <summary>
/// A WPF control for viewing and interacting with database tables.
/// </summary>
public partial class TableViewer : UserControl
{
#region Enumerables
/// <summary>
/// Defines the selection states supported by the table viewer.
/// </summary>
private enum SelectionMode : byte
{
CellSelect = 0,
RowSelect = 1,
ColumnSelect = 2,
None = 3,
All = 4,
EditSelect = 5
}
/// <summary>
/// Defines the sort state applied to a table column.
/// </summary>
private enum SortOrder : byte
{
Ascending = 2,
Descending = 1,
None = 0
}
#endregion
#region Fields
private int _visibleRowCount;
private bool _isLoaded = false;
private int _activeCellDataColumnIndex = 0;
private int _activeCellVirtualRowIndex = 0;
private int _mouseDownVirtualRowIndex;
private int _mouseDownColumnIndex;
private SelectionMode _mouseSelectionMode = SelectionMode.None;
private List<int> _selectedDataRowIndices = new List<int>();
private List<int> _selectedColumnIndices = new List<int>();
private SortedDictionary<int, SortedSet<int>> _selectedCellIndices = new SortedDictionary<int, SortedSet<int>>();
private bool _selectedRowsOnly = false;
private bool _visualRefreshPending = false;
private string _attributeSelectorString = "";
private int[]? _rowOffset;
private int[]? _rowId;
private int[]? _sortedSelectedRowOffsets;
private SortOrder _columnSortOrder;
private SortOrder[]? _columnsSortedOrder;
private GridLength[]? _columnWidths;
private readonly TextBox _cellEditTextBox;
private string _fieldCalculatorString = "";
private HashSet<int> _readOnlyColumns = new HashSet<int>();
#endregion
#region Dependency Properties
/// <summary>
/// Identifies the <see cref="DataView"/> dependency property.
/// </summary>
public static readonly DependencyProperty DataViewProperty = DependencyProperty.Register(
nameof(DataView), typeof(DataTableView), typeof(TableViewer),
new UIPropertyMetadata(null, new PropertyChangedCallback(LoadView)));
/// <summary>
/// Identifies the <see cref="AllCellsSelected"/> dependency property.
/// </summary>
public static readonly DependencyProperty AllCellsSelectedProperty = DependencyProperty.Register(
nameof(AllCellsSelected), typeof(bool), typeof(TableViewer), new UIPropertyMetadata(false, OnAllCellsSelectedChanged));
/// <summary>
/// Updates the select-all button when the all-cells selection state changes.
/// </summary>
/// <param name="d">The table viewer whose property changed.</param>
/// <param name="e">The dependency-property change details.</param>
private static void OnAllCellsSelectedChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
if (d is TableViewer viewer)
viewer.UpdateSelectAllButton();
}
/// <summary>
/// Identifies the <see cref="RowHeight"/> dependency property.
/// </summary>
public static readonly DependencyProperty RowHeightProperty = DependencyProperty.Register(
nameof(RowHeight), typeof(double), typeof(TableViewer), new UIPropertyMetadata(23.0));
/// <summary>
/// Identifies the <see cref="ColumnHeaderHeight"/> dependency property.
/// </summary>
public static readonly DependencyProperty ColumnHeaderHeightProperty = DependencyProperty.Register(
nameof(ColumnHeaderHeight), typeof(GridLength), typeof(TableViewer), new UIPropertyMetadata(GridLength.Auto));
/// <summary>
/// Identifies the <see cref="ColumnHeaderTextblockStyle"/> dependency property.
/// </summary>
public static readonly DependencyProperty ColumnHeaderTextblockStyleProperty = DependencyProperty.Register(
nameof(ColumnHeaderTextblockStyle), typeof(Style), typeof(TableViewer), new PropertyMetadata(GetDefaultColumnHeaderTextblockStyle()));
/// <summary>
/// Identifies the <see cref="ColumnHeaderBorderStyle"/> dependency property.
/// </summary>
public static readonly DependencyProperty ColumnHeaderBorderStyleProperty = DependencyProperty.Register(
nameof(ColumnHeaderBorderStyle), typeof(Style), typeof(TableViewer), new PropertyMetadata(GetDefaultColumnHeaderBorderStyle()));
/// <summary>
/// Identifies the <see cref="RowHeaderTextblockStyle"/> dependency property.
/// </summary>
public static readonly DependencyProperty RowHeaderTextblockStyleProperty = DependencyProperty.Register(
nameof(RowHeaderTextblockStyle), typeof(Style), typeof(TableViewer), new PropertyMetadata(GetDefaultRowHeaderTextblockStyle()));
/// <summary>
/// Identifies the <see cref="RowHeaderBorderStyle"/> dependency property.
/// </summary>
public static readonly DependencyProperty RowHeaderBorderStyleProperty = DependencyProperty.Register(
nameof(RowHeaderBorderStyle), typeof(Style), typeof(TableViewer), new PropertyMetadata(GetDefaultRowHeaderBorderStyle()));
/// <summary>
/// Identifies the <see cref="ShowRowHeaders"/> dependency property.
/// </summary>
public static readonly DependencyProperty ShowRowHeadersProperty = DependencyProperty.Register(
nameof(ShowRowHeaders), typeof(bool), typeof(TableViewer), new UIPropertyMetadata(true));
/// <summary>
/// Identifies the <see cref="Editable"/> dependency property.
/// </summary>
public static readonly DependencyProperty EditableProperty = DependencyProperty.Register(
nameof(Editable), typeof(bool), typeof(TableViewer), new UIPropertyMetadata(false, OnEditableChanged));
/// <summary>
/// Updates paste availability when editability changes.
/// </summary>
/// <param name="d">The table viewer whose property changed.</param>
/// <param name="e">The dependency-property change details.</param>
private static void OnEditableChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
if (d is TableViewer tv) tv.UpdatePasteButtonState();
}
/// <summary>
/// Identifies the <see cref="HasFieldCalculator"/> dependency property.
/// </summary>
public static readonly DependencyProperty HasFieldCalculatorProperty = DependencyProperty.Register(
nameof(HasFieldCalculator), typeof(bool), typeof(TableViewer), new UIPropertyMetadata(true));
/// <summary>
/// Identifies the <see cref="HasSaveButton"/> dependency property.
/// </summary>
public static readonly DependencyProperty HasSaveButtonProperty = DependencyProperty.Register(
nameof(HasSaveButton), typeof(bool), typeof(TableViewer), new UIPropertyMetadata(true));
/// <summary>
/// Identifies the <see cref="HasUndoRedoButtons"/> dependency property.
/// </summary>
public static readonly DependencyProperty HasUndoRedoButtonsProperty = DependencyProperty.Register(
nameof(HasUndoRedoButtons), typeof(bool), typeof(TableViewer), new UIPropertyMetadata(true));
/// <summary>
/// Identifies the <see cref="RowSelectable"/> dependency property.
/// </summary>
public static readonly DependencyProperty RowSelectableProperty = DependencyProperty.Register(
nameof(RowSelectable), typeof(bool), typeof(TableViewer), new UIPropertyMetadata(true));
/// <summary>
/// Identifies the <see cref="CellTextblockStyle"/> dependency property.
/// </summary>
public static readonly DependencyProperty CellTextblockStyleProperty = DependencyProperty.Register(
nameof(CellTextblockStyle), typeof(Style), typeof(TableViewer), new PropertyMetadata(GetDefaultCellTextblockStyle()));
/// <summary>
/// Identifies the <see cref="SelectedColor"/> dependency property.
/// </summary>
public static readonly DependencyProperty SelectedColorProperty = DependencyProperty.Register(
nameof(SelectedColor), typeof(Brush), typeof(TableViewer), new UIPropertyMetadata(new SolidColorBrush(Color.FromArgb(240, 0, 120, 215)), OnVisualPropertyChanged));
/// <summary>
/// Identifies the <see cref="InactiveSelectedColor"/> dependency property.
/// </summary>
public static readonly DependencyProperty InactiveSelectedColorProperty = DependencyProperty.Register(
nameof(InactiveSelectedColor), typeof(Brush), typeof(TableViewer), new UIPropertyMetadata(new SolidColorBrush(Color.FromRgb(196, 213, 240)), OnVisualPropertyChanged));
/// <summary>
/// Identifies the <see cref="ActiveCellForeground"/> dependency property.
/// </summary>
public static readonly DependencyProperty ActiveCellForegroundProperty = DependencyProperty.Register(
nameof(ActiveCellForeground), typeof(Brush), typeof(TableViewer), new UIPropertyMetadata(new SolidColorBrush(Colors.White), OnVisualPropertyChanged));
/// <summary>
/// Identifies the <see cref="ActiveCellBackground"/> dependency property.
/// </summary>
public static readonly DependencyProperty ActiveCellBackgroundProperty = DependencyProperty.Register(
nameof(ActiveCellBackground), typeof(Brush), typeof(TableViewer), new UIPropertyMetadata(new SolidColorBrush(Color.FromArgb(255, 21, 107, 176)), OnVisualPropertyChanged));
/// <summary>
/// Identifies the <see cref="DeSelectedColor"/> dependency property.
/// </summary>
public static readonly DependencyProperty DeSelectedColorProperty = DependencyProperty.Register(
nameof(DeSelectedColor), typeof(Brush), typeof(TableViewer), new UIPropertyMetadata(Brushes.Transparent, OnVisualPropertyChanged));
/// <summary>
/// Identifies the <see cref="SelectedForegroundColor"/> dependency property.
/// </summary>
public static readonly DependencyProperty SelectedForegroundColorProperty = DependencyProperty.Register(
nameof(SelectedForegroundColor), typeof(Brush), typeof(TableViewer), new UIPropertyMetadata(new SolidColorBrush(Colors.White), OnVisualPropertyChanged));
/// <summary>
/// Identifies the <see cref="InactiveSelectedForegroundColor"/> dependency property.
/// </summary>
public static readonly DependencyProperty InactiveSelectedForegroundColorProperty = DependencyProperty.Register(
nameof(InactiveSelectedForegroundColor), typeof(Brush), typeof(TableViewer), new UIPropertyMetadata(new SolidColorBrush(Color.FromRgb(30, 30, 30)), OnVisualPropertyChanged));
/// <summary>
/// Identifies the <see cref="DeSelectedForegroundColor"/> dependency property.
/// </summary>
public static readonly DependencyProperty DeSelectedForegroundColorProperty = DependencyProperty.Register(
nameof(DeSelectedForegroundColor), typeof(Brush), typeof(TableViewer), new UIPropertyMetadata(Brushes.Black, OnVisualPropertyChanged));
/// <summary>
/// Identifies the <see cref="RowColor"/> dependency property.
/// </summary>
public static readonly DependencyProperty RowColorProperty = DependencyProperty.Register(
nameof(RowColor), typeof(Brush), typeof(TableViewer), new UIPropertyMetadata(Brushes.White, OnVisualPropertyChanged));
/// <summary>
/// Identifies the <see cref="AlternateRowColor"/> dependency property.
/// </summary>
public static readonly DependencyProperty AlternateRowColorProperty = DependencyProperty.Register(
nameof(AlternateRowColor), typeof(Brush), typeof(TableViewer), new UIPropertyMetadata(new SolidColorBrush(Color.FromArgb(255, 243, 249, 247)), OnVisualPropertyChanged));
/// <summary>
/// Identifies the <see cref="RowLineColor"/> dependency property.
/// </summary>
public static readonly DependencyProperty RowLineColorProperty = DependencyProperty.Register(
nameof(RowLineColor), typeof(Brush), typeof(TableViewer), new UIPropertyMetadata(new SolidColorBrush(Color.FromArgb(255, 53, 59, 122)), OnVisualPropertyChanged));
/// <summary>
/// Identifies the <see cref="RowLineThickness"/> dependency property.
/// </summary>
public static readonly DependencyProperty RowLineThicknessProperty = DependencyProperty.Register(
nameof(RowLineThickness), typeof(double), typeof(TableViewer), new UIPropertyMetadata(1.0, OnVisualPropertyChanged));
/// <summary>
/// Identifies the <see cref="ColumnLineColor"/> dependency property.
/// </summary>
public static readonly DependencyProperty ColumnLineColorProperty = DependencyProperty.Register(
nameof(ColumnLineColor), typeof(Brush), typeof(TableViewer), new UIPropertyMetadata(new SolidColorBrush(Color.FromArgb(255, 53, 59, 122)), OnVisualPropertyChanged));
/// <summary>
/// Identifies the <see cref="ColumnLineThickness"/> dependency property.
/// </summary>
public static readonly DependencyProperty ColumnLineThicknessProperty = DependencyProperty.Register(
nameof(ColumnLineThickness), typeof(double), typeof(TableViewer), new UIPropertyMetadata(1.0, OnVisualPropertyChanged));
/// <summary>
/// Identifies the <see cref="ColumnSelectable"/> dependency property.
/// </summary>
public static readonly DependencyProperty ColumnSelectableProperty = DependencyProperty.Register(
nameof(ColumnSelectable), typeof(bool), typeof(TableViewer), new UIPropertyMetadata(true));
/// <summary>
/// Identifies the <see cref="CellSelectable"/> dependency property.
/// </summary>
public static readonly DependencyProperty CellSelectableProperty = DependencyProperty.Register(
nameof(CellSelectable), typeof(bool), typeof(TableViewer), new UIPropertyMetadata(true));
/// <summary>
/// Identifies the <see cref="AutoFitColumns"/> dependency property.
/// </summary>
public static readonly DependencyProperty AutoFitColumnsProperty = DependencyProperty.Register(
nameof(AutoFitColumns), typeof(bool), typeof(TableViewer), new UIPropertyMetadata(false));
#endregion
#region Properties
/// <summary>
/// Gets or sets the data source for the table viewer.
/// </summary>
/// <value>The <see cref="DataTableView"/> containing the data to display.</value>
public DataTableView DataView
{
get => (DataTableView)GetValue(DataViewProperty);
set => SetValue(DataViewProperty, value);
}
/// <summary>
/// Gets a value indicating whether only selected rows are currently being displayed.
/// </summary>
/// <value><c>true</c> if showing selected rows only; otherwise, <c>false</c>.</value>
public bool ShowingSelectedRowsOnly => _selectedRowsOnly;
/// <summary>
/// Gets the list of currently selected row indices in the data table.
/// </summary>
/// <value>A list of zero-based row indices that are currently selected.</value>
public List<int> GetSelectedRows => _selectedDataRowIndices;
/// <summary>
/// Gets the row index of the currently active cell.
/// </summary>
/// <value>The zero-based row index of the active cell in the virtual (visible) grid.</value>
public int ActiveCellRowIndex => _activeCellVirtualRowIndex;
/// <summary>
/// Gets the column index of the currently active cell.
/// </summary>
/// <value>The zero-based column index of the active cell in the data table.</value>
public int ActiveCellColumnIndex => _activeCellDataColumnIndex;
/// <summary>
/// Gets or sets a value indicating whether all cells in the table are selected.
/// </summary>
/// <value><c>true</c> if all cells are selected; otherwise, <c>false</c>.</value>
public bool AllCellsSelected
{
get => (bool)GetValue(AllCellsSelectedProperty);
set => SetValue(AllCellsSelectedProperty, value);
}
/// <summary>
/// Gets or sets the height of each data row in pixels.
/// </summary>
/// <value>The row height in pixels. Default is 23.0.</value>
public double RowHeight
{
get => (double)GetValue(RowHeightProperty);
set => SetValue(RowHeightProperty, value);
}
/// <summary>
/// Gets or sets the height of the column header row.
/// </summary>
/// <value>The column header height as a <see cref="GridLength"/>. Default is Auto.</value>
public GridLength ColumnHeaderHeight
{
get => (GridLength)GetValue(ColumnHeaderHeightProperty);
set => SetValue(ColumnHeaderHeightProperty, value);
}
/// <summary>
/// Gets or sets the style applied to column header text blocks.
/// </summary>
/// <value>The <see cref="Style"/> for column header TextBlock elements.</value>
public Style ColumnHeaderTextblockStyle
{
get => (Style)GetValue(ColumnHeaderTextblockStyleProperty);
set => SetValue(ColumnHeaderTextblockStyleProperty, value);
}
/// <summary>
/// Gets or sets the style applied to column header borders.
/// </summary>
/// <value>The <see cref="Style"/> for column header Border elements.</value>
public Style ColumnHeaderBorderStyle
{
get => (Style)GetValue(ColumnHeaderBorderStyleProperty);
set => SetValue(ColumnHeaderBorderStyleProperty, value);
}
/// <summary>
/// Gets or sets the style applied to row header text blocks.
/// </summary>
/// <value>The <see cref="Style"/> for row header TextBlock elements.</value>
public Style RowHeaderTextblockStyle
{
get => (Style)GetValue(RowHeaderTextblockStyleProperty);
set => SetValue(RowHeaderTextblockStyleProperty, value);
}
/// <summary>
/// Gets or sets the style applied to row header borders.
/// </summary>
/// <value>The <see cref="Style"/> for row header Border elements.</value>
public Style RowHeaderBorderStyle
{
get => (Style)GetValue(RowHeaderBorderStyleProperty);
set => SetValue(RowHeaderBorderStyleProperty, value);
}
/// <summary>
/// Gets or sets a value indicating whether row headers are visible.
/// </summary>
/// <value><c>true</c> to show row headers; otherwise, <c>false</c>. Default is <c>true</c>.</value>
public bool ShowRowHeaders
{
get => (bool)GetValue(ShowRowHeadersProperty);
set => SetValue(ShowRowHeadersProperty, value);
}
/// <summary>
/// Gets or sets a value indicating whether cells can be edited.
/// </summary>
/// <value><c>true</c> if the table is editable; otherwise, <c>false</c>. Default is <c>false</c>.</value>
public bool Editable
{
get => (bool)GetValue(EditableProperty);
set => SetValue(EditableProperty, value);
}
/// <summary>
/// Gets or sets a value indicating whether the field calculator button is visible.
/// </summary>
/// <value><c>true</c> to show the field calculator; otherwise, <c>false</c>. Default is <c>true</c>.</value>
public bool HasFieldCalculator
{
get => (bool)GetValue(HasFieldCalculatorProperty);
set => SetValue(HasFieldCalculatorProperty, value);
}
/// <summary>
/// Gets or sets a value indicating whether the save button is visible.
/// </summary>
/// <value><c>true</c> to show the save button; otherwise, <c>false</c>. Default is <c>true</c>.</value>
public bool HasSaveButton
{
get => (bool)GetValue(HasSaveButtonProperty);
set => SetValue(HasSaveButtonProperty, value);
}
/// <summary>
/// Gets or sets a value indicating whether the undo/redo buttons are visible.
/// </summary>
/// <value><c>true</c> to show undo/redo buttons; otherwise, <c>false</c>. Default is <c>true</c>.</value>
public bool HasUndoRedoButtons
{
get => (bool)GetValue(HasUndoRedoButtonsProperty);
set => SetValue(HasUndoRedoButtonsProperty, value);
}
/// <summary>
/// Gets or sets a value indicating whether entire rows can be selected.
/// </summary>
/// <value><c>true</c> to allow row selection; otherwise, <c>false</c>. Default is <c>true</c>.</value>
public bool RowSelectable
{
get => (bool)GetValue(RowSelectableProperty);
set => SetValue(RowSelectableProperty, value);
}
/// <summary>
/// Gets or sets the style applied to cell text blocks.
/// </summary>
/// <value>The <see cref="Style"/> for cell TextBlock elements.</value>
public Style CellTextblockStyle
{
get => (Style)GetValue(CellTextblockStyleProperty);
set => SetValue(CellTextblockStyleProperty, value);
}
/// <summary>
/// Gets or sets the background color for selected cells.
/// </summary>
/// <value>The <see cref="Brush"/> used to fill selected cells.</value>
public Brush SelectedColor
{
get => (Brush)GetValue(SelectedColorProperty);
set => SetValue(SelectedColorProperty, value);
}
/// <summary>
/// Gets or sets the background color for selected cells when table selection is inactive.
/// </summary>
/// <value>The <see cref="Brush"/> used to fill inactive selected cells.</value>
public Brush InactiveSelectedColor
{
get => (Brush)GetValue(InactiveSelectedColorProperty);
set => SetValue(InactiveSelectedColorProperty, value);
}
/// <summary>
/// Gets or sets the foreground color for the active cell.
/// </summary>
/// <value>The <see cref="Brush"/> used for the active cell's text.</value>
public Brush ActiveCellForeground
{
get => (Brush)GetValue(ActiveCellForegroundProperty);
set => SetValue(ActiveCellForegroundProperty, value);
}
/// <summary>
/// Gets or sets the background color for the active cell.
/// </summary>
/// <value>The <see cref="Brush"/> used to fill the active cell.</value>
public Brush ActiveCellBackground
{
get => (Brush)GetValue(ActiveCellBackgroundProperty);
set => SetValue(ActiveCellBackgroundProperty, value);
}
/// <summary>
/// Gets or sets the background color for deselected cells.
/// </summary>
/// <value>The <see cref="Brush"/> used to fill deselected cells.</value>
public Brush DeSelectedColor
{
get => (Brush)GetValue(DeSelectedColorProperty);
set => SetValue(DeSelectedColorProperty, value);
}
/// <summary>
/// Gets or sets the foreground color for selected cells.
/// </summary>
/// <value>The <see cref="Brush"/> used for selected cell text.</value>
public Brush SelectedForegroundColor
{
get => (Brush)GetValue(SelectedForegroundColorProperty);
set => SetValue(SelectedForegroundColorProperty, value);
}
/// <summary>
/// Gets or sets the foreground color for selected cells when table selection is inactive.
/// </summary>
/// <value>The <see cref="Brush"/> used for inactive selected cell text.</value>
public Brush InactiveSelectedForegroundColor
{
get => (Brush)GetValue(InactiveSelectedForegroundColorProperty);
set => SetValue(InactiveSelectedForegroundColorProperty, value);
}
/// <summary>
/// Gets or sets the foreground color for deselected cells.
/// </summary>
/// <value>The <see cref="Brush"/> used for deselected cell text.</value>
public Brush DeSelectedForegroundColor
{
get => (Brush)GetValue(DeSelectedForegroundColorProperty);
set => SetValue(DeSelectedForegroundColorProperty, value);
}
/// <summary>
/// Gets or sets the background color for odd-numbered rows.
/// </summary>
/// <value>The <see cref="Brush"/> used to fill odd rows.</value>
public Brush RowColor
{
get => (Brush)GetValue(RowColorProperty);
set => SetValue(RowColorProperty, value);
}
/// <summary>
/// Gets or sets the background color for even-numbered rows.
/// </summary>
/// <value>The <see cref="Brush"/> used to fill even rows.</value>
public Brush AlternateRowColor
{
get => (Brush)GetValue(AlternateRowColorProperty);
set => SetValue(AlternateRowColorProperty, value);
}
/// <summary>
/// Gets or sets the color of horizontal row separator lines.
/// </summary>
/// <value>The <see cref="Brush"/> used for row lines.</value>
public Brush RowLineColor
{
get => (Brush)GetValue(RowLineColorProperty);
set => SetValue(RowLineColorProperty, value);
}
/// <summary>
/// Gets or sets the thickness of horizontal row separator lines.
/// </summary>
/// <value>The line thickness in pixels. Default is 1.0.</value>
public double RowLineThickness
{
get => (double)GetValue(RowLineThicknessProperty);
set => SetValue(RowLineThicknessProperty, value);
}
/// <summary>
/// Gets or sets the color of vertical column separator lines.
/// </summary>
/// <value>The <see cref="Brush"/> used for column lines.</value>
public Brush ColumnLineColor
{
get => (Brush)GetValue(ColumnLineColorProperty);
set => SetValue(ColumnLineColorProperty, value);
}
/// <summary>
/// Gets or sets the thickness of vertical column separator lines.
/// </summary>
/// <value>The line thickness in pixels. Default is 1.0.</value>
public double ColumnLineThickness
{
get => (double)GetValue(ColumnLineThicknessProperty);
set => SetValue(ColumnLineThicknessProperty, value);
}
/// <summary>
/// Gets or sets a value indicating whether entire columns can be selected.
/// </summary>
/// <value><c>true</c> to allow column selection; otherwise, <c>false</c>. Default is <c>true</c>.</value>
public bool ColumnSelectable
{
get => (bool)GetValue(ColumnSelectableProperty);
set => SetValue(ColumnSelectableProperty, value);
}
/// <summary>
/// Gets or sets a value indicating whether individual cells can be selected.
/// </summary>
/// <value><c>true</c> to allow cell selection; otherwise, <c>false</c>. Default is <c>true</c>.</value>
public bool CellSelectable
{
get => (bool)GetValue(CellSelectableProperty);
set => SetValue(CellSelectableProperty, value);
}
/// <summary>
/// Gets or sets a value indicating whether column widths are automatically adjusted to fit content.
/// </summary>
/// <value><c>true</c> to auto-fit columns; otherwise, <c>false</c>. Default is <c>false</c>.</value>
public bool AutoFitColumns
{
get => (bool)GetValue(AutoFitColumnsProperty);
set => SetValue(AutoFitColumnsProperty, value);
}
#endregion
#region Events
/// <summary>
/// Event handler delegate for selected row indices changed event.
/// </summary>
/// <param name="selectedRowIndices">The list of selected row indices.</param>
public delegate void SelectedRowIndicesChangedEventHandler(List<int> selectedRowIndices);
/// <summary>
/// Event handler delegate for row right button up event.
/// </summary>
/// <param name="rowUpMenu">The context menu for the row.</param>
/// <param name="dataRowIndex">The data row index.</param>
public delegate void RowRightButtonUpEventHandler(ContextMenu rowUpMenu, int dataRowIndex);
/// <summary>
/// Occurs when the set of selected row indices changes.
/// </summary>
public event SelectedRowIndicesChangedEventHandler? SelectedRowIndicesChanged;
/// <summary>
/// Occurs when the active cell location changes.
/// </summary>
public event Action? ActiveCellLocationChanged;
/// <summary>
/// Occurs when the right mouse button is released on a row header.
/// Provides the context menu and row index for custom menu handling.
/// </summary>
public event RowRightButtonUpEventHandler? RowRightButtonUp;
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="TableViewer"/> class.
/// </summary>
public TableViewer()
{
InitializeComponent();
_cellEditTextBox = new TextBox { Padding = new Thickness(0, 3, 0, 2), Margin = new Thickness(0, 0, 0, 1) };
_cellEditTextBox.PreviewKeyDown += PreviewEditText;
_cellEditTextBox.LostFocus += EditTextLostFocus;
EditorToolbar.IsEnabled = false;
GotFocus += (_, _) => UpdatePasteButtonState();
IsKeyboardFocusWithinChanged += TableSelectionFocusWithinChanged;
GridPanel.GotKeyboardFocus += TableSelectionFocusChanged;
GridPanel.LostKeyboardFocus += TableSelectionFocusChanged;
}
#endregion
#region Loading
/// <summary>
/// Schedules a visual refresh after a styling dependency property changes.
/// </summary>
/// <param name="d">The table viewer whose visual property changed.</param>
/// <param name="e">The dependency-property change details.</param>
private static void OnVisualPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
if (d is not TableViewer tv) return;
if (tv.DataView == null || tv.GridPanel.Children.Count == 0) return;
// Coalesce multiple DP changes (e.g. theme switch updates many colors at once)
// into a single visual refresh via dispatcher.
if (!tv._visualRefreshPending)
{
tv._visualRefreshPending = true;
tv.Dispatcher.InvokeAsync(() =>
{
tv._visualRefreshPending = false;
if (tv.DataView == null || tv.GridPanel.Children.Count == 0) return;
tv.LoadRows();
// Update column grid line colors (not recreated by LoadRows)
int colLineCount = tv.DataView.ColumnNames.Count() + 1;
for (int i = 0; i < colLineCount && i < tv.GridLinesCanvas.Children.Count; i++)
{
if (tv.GridLinesCanvas.Children[i] is Line colLine)
colLine.Stroke = tv.ColumnLineColor;
}
// Update column header border brushes and top boundary line (not recreated by LoadRows)
var headerBorderBrush = (Brush)tv.FindResource("DataGrid.Header.Border");
foreach (UIElement child in tv.ColumnHeadersGrid.Children)
{
if (child is ColumnHeader header)
header.BorderBrush = headerBorderBrush;
}
// Update the initial row line (top boundary between headers and cells)
int topLineIndex = tv.DataView.ColumnNames.Count() + 1;
if (topLineIndex < tv.GridLinesCanvas.Children.Count &&
tv.GridLinesCanvas.Children[topLineIndex] is Line topLine)
{
topLine.Stroke = headerBorderBrush;
}
tv.DeSelectAllCells();
tv.SetSelectedCells();
tv.UpdateRowHeaders();
}, System.Windows.Threading.DispatcherPriority.Render);
}
}
/// <summary>
/// Handles table body keyboard focus changes by repainting selected cells with active or inactive selection brushes.
/// </summary>
/// <param name="sender">The source of the keyboard focus change.</param>
/// <param name="e">The keyboard focus event data.</param>
private void TableSelectionFocusChanged(object sender, KeyboardFocusChangedEventArgs e)
{
RefreshSelectionVisuals();
}
/// <summary>
/// Handles control-wide keyboard focus changes by repainting selected cells with active or inactive selection brushes.
/// </summary>
/// <param name="sender">The source of the keyboard focus change.</param>
/// <param name="e">The focus-within property change data.</param>
private void TableSelectionFocusWithinChanged(object sender, DependencyPropertyChangedEventArgs e)
{
RefreshSelectionVisuals();
}
/// <summary>
/// Attaches a new <see cref="DataView"/> and rebuilds table state for it.
/// </summary>
/// <param name="d">The table viewer whose data view changed.</param>
/// <param name="e">The dependency-property change details.</param>
private static void LoadView(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
if (d == null || d.GetType() != typeof(TableViewer)) return;
var thisControl = (TableViewer)d;
if (e.OldValue != null && e.OldValue is DataTableView oldView)
{
oldView.RowsAdded -= thisControl.TableViewRowsAdded;
oldView.RowsDeleted -= thisControl.TableViewRowsDeleted;
oldView.ColumnsAdded -= thisControl.TableViewColumnsAdded;
oldView.ColumnsDeleted -= thisControl.TableViewColumnsDeleted;
}
if (e.NewValue == null || !(e.NewValue is DataTableView))
{
thisControl._selectedCellIndices = new SortedDictionary<int, SortedSet<int>>();
thisControl._selectedColumnIndices = new List<int>();
thisControl._selectedDataRowIndices = new List<int>();
thisControl._activeCellDataColumnIndex = 0;
thisControl._activeCellVirtualRowIndex = 0;
thisControl._selectedRowsOnly = false;
thisControl.ColumnHeadersGrid.SizeChanged -= thisControl.ColumnsGridSizeChanged;
thisControl.GridPanel.Children.Clear();
thisControl.RowHeadersGrid.Children.Clear();
thisControl.RowColorGrid.Children.Clear();
thisControl.ColumnHeadersGrid.Children.Clear();
thisControl.GridPanel.RowDefinitions.Clear();
thisControl.RowHeadersGrid.RowDefinitions.Clear();
thisControl.RowColorGrid.RowDefinitions.Clear();
thisControl.ColumnHeadersGrid.ColumnDefinitions.Clear();
thisControl.GridPanel.ColumnDefinitions.Clear();
thisControl.GridLinesCanvas.Children.Clear();
thisControl.SelectionToolbar.IsEnabled = false;
thisControl.EditorToolbar.IsEnabled = false;
}
else
{
var newView = (DataTableView)e.NewValue;
newView.RowsAdded += thisControl.TableViewRowsAdded;
newView.RowsDeleted += thisControl.TableViewRowsDeleted;
newView.ColumnsAdded += thisControl.TableViewColumnsAdded;
newView.ColumnsDeleted += thisControl.TableViewColumnsDeleted;
if (!newView.ParentDatabase.DataBaseOpen)
{
try
{
newView.ParentDatabase.Open();
}
catch (Exception ex)
{
MessageBox.Show($"Failed to open database: {ex.Message}", "Database Error", MessageBoxButton.OK, MessageBoxImage.Error);
return;
}
}
thisControl._columnSortOrder = SortOrder.None;
thisControl._columnsSortedOrder = new SortOrder[newView.ColumnNames.Count()];
thisControl.Refresh();
if (thisControl.ShowRowHeaders)
{
double pixelsPerDip = VisualTreeHelper.GetDpi(thisControl).PixelsPerDip;
thisControl.RowHeadersColumnDefinition.Width = new GridLength(
(int)(new FormattedText(newView.NumberOfRows.ToString(), CultureInfo.GetCultureInfo("en-us"),
FlowDirection.LeftToRight, new Typeface(new FontFamily("Segoe UI"), FontStyles.Normal, FontWeights.Bold, FontStretches.Normal),
12, Brushes.Black, pixelsPerDip).Width) + 10);
}
thisControl.SelectionToolbar.IsEnabled = true;
thisControl.EditorToolbar.IsEnabled = true;
}
}
/// <summary>
/// Marks the specified columns as read-only, preventing edits to their cells.
/// </summary>
/// <param name="columnIndices">Array of zero-based column indices to mark as read-only.</param>
public void SetColumnsAsReadOnly(int[] columnIndices)
{
foreach (var idx in columnIndices) _readOnlyColumns.Add(idx);
}
/// <summary>
/// Marks the specified columns as read-only by column name, preventing edits to their cells.
/// </summary>
/// <param name="columnNames">Array of column names to mark as read-only.</param>
public void SetColumnsAsReadOnly(string[] columnNames)
{
foreach (var name in columnNames)
{
int idx = Array.IndexOf(DataView.ColumnNames, name);
if (idx >= 0) _readOnlyColumns.Add(idx);
}
}
#endregion
#region Database Events
/// <summary>
/// Handles the event when columns are deleted from the data view.
/// Updates selection indices, active cell position, and sort order accordingly.
/// </summary>
/// <param name="columnIndices">Array of indices of the deleted columns.</param>
private void TableViewColumnsDeleted(int[] columnIndices)
{
Array.Sort(columnIndices);
for (int i = columnIndices.Length - 1; i >= 0; i--)
{
// Update selected column indices
_selectedColumnIndices.Remove(columnIndices[i]);
for (int j = 0; j < _selectedColumnIndices.Count; j++)
if (_selectedColumnIndices[j] > columnIndices[i]) _selectedColumnIndices[j] -= 1;
// Delete column from selected cells collection
var keysToRemove = new List<int>();
foreach (var selectedCellsByRow in _selectedCellIndices)
{
selectedCellsByRow.Value.Remove(columnIndices[i]);
if (selectedCellsByRow.Value.Count == 0) keysToRemove.Add(selectedCellsByRow.Key);
}
foreach (var keyToRemove in keysToRemove)
_selectedCellIndices.Remove(keyToRemove);
foreach (var selectedCellsByRow in _selectedCellIndices)
{
var columnsToUpdate = new List<int>();
foreach (var selectedCellColumn in selectedCellsByRow.Value)
if (selectedCellColumn >= columnIndices[i]) columnsToUpdate.Add(selectedCellColumn);
foreach (var columnToUpdate in columnsToUpdate)
selectedCellsByRow.Value.Remove(columnToUpdate);
foreach (var columnToUpdate in columnsToUpdate)
selectedCellsByRow.Value.Add(columnToUpdate - 1);
}
// Update active cell
if (_activeCellDataColumnIndex >= columnIndices[i]) _activeCellDataColumnIndex -= 1;
if (_activeCellDataColumnIndex < 0) _activeCellDataColumnIndex = 0;
// Update sort order
if (_columnsSortedOrder![columnIndices[i]] != SortOrder.None) RemoveSort();
var updated = new SortOrder[_columnsSortedOrder.Length - 1];
for (int j = 0; j < columnIndices[i]; j++) updated[j] = _columnsSortedOrder[j];
for (int j = columnIndices[i]; j < _columnsSortedOrder.Length - 1; j++) updated[j] = _columnsSortedOrder[j + 1];
_columnsSortedOrder = updated;
}
// Update undo and redo buttons if needed
UpdateUndoRedoButtons();
// Refresh viewer to include new column
NumberOfColumnsChanged();
}
/// <summary>
/// Handles the event when columns are added to the data view.
/// Updates selection indices, active cell position, and sort order accordingly.
/// </summary>
/// <param name="columnIndices">Array of indices where columns were added.</param>
private void TableViewColumnsAdded(int[] columnIndices)
{
Array.Sort(columnIndices);
for (int i = 0; i < columnIndices.Length; i++)
{
// Update selected column indices
for (int j = 0; j < _selectedColumnIndices.Count; j++)
if (_selectedColumnIndices[j] >= columnIndices[i]) _selectedColumnIndices[j] += 1;
// Adjust column in selected cells collection
foreach (var selectedCellsByRow in _selectedCellIndices)
{
var columnsToUpdate = new List<int>();
foreach (var selectedCellColumn in selectedCellsByRow.Value)
if (selectedCellColumn >= columnIndices[i]) columnsToUpdate.Add(selectedCellColumn);
foreach (var columnToUpdate in columnsToUpdate)
selectedCellsByRow.Value.Remove(columnToUpdate);
foreach (var columnToUpdate in columnsToUpdate)
selectedCellsByRow.Value.Add(columnToUpdate + 1);
}
// Update active cell
if (_activeCellDataColumnIndex >= columnIndices[i]) _activeCellDataColumnIndex += 1;
if (_activeCellDataColumnIndex > DataView.ColumnNames.Count() - 1)
_activeCellDataColumnIndex = DataView.ColumnNames.Count() - 1;
// Update sort order
var updated = new SortOrder[_columnsSortedOrder!.Length + 1];
for (int j = 0; j < columnIndices[i]; j++) updated[j] = _columnsSortedOrder[j];
updated[columnIndices[i]] = SortOrder.None;
for (int j = columnIndices[i] + 1; j < updated.Length; j++) updated[j] = _columnsSortedOrder[j - 1];
_columnsSortedOrder = updated;
}
UpdateUndoRedoButtons();
NumberOfColumnsChanged();
}
/// <summary>
/// Handles the event when rows are added to the data view.
/// Updates selection indices and active cell position accordingly.
/// </summary>
/// <param name="rowIndices">Array of indices where rows were added.</param>
private void TableViewRowsAdded(int[] rowIndices)
{
Array.Sort(rowIndices);
for (int i = 0; i < rowIndices.Length; i++)
{
// Update selected row indices
for (int j = 0; j < _selectedDataRowIndices.Count; j++)
if (_selectedDataRowIndices[j] >= rowIndices[i]) _selectedDataRowIndices[j] += 1;
// Adjust row in selected cells collection
var rowsToUpdate = new List<int>();
foreach (var selectedCellsByRow in _selectedCellIndices)
if (selectedCellsByRow.Key >= rowIndices[i]) rowsToUpdate.Add(selectedCellsByRow.Key);
rowsToUpdate.Sort();
rowsToUpdate.Reverse();
foreach (var rowToUpdate in rowsToUpdate)
{
_selectedCellIndices.Add(rowToUpdate + 1, _selectedCellIndices[rowToUpdate]);
_selectedCellIndices.Remove(rowToUpdate);
}
// Update active cell