DynamicGridGridUIComponent.cs 69 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035
  1. using InABox.Clients;
  2. using InABox.Core;
  3. using InABox.Scripting;
  4. using InABox.Wpf;
  5. using InABox.WPF;
  6. using Microsoft.Xaml.Behaviors;
  7. using org.omg.PortableInterceptor;
  8. using sun.reflect.generics.tree;
  9. using sun.util.resources.cldr.fr;
  10. using Syncfusion.Data;
  11. using Syncfusion.Data.Extensions;
  12. using Syncfusion.UI.Xaml.Grid;
  13. using Syncfusion.UI.Xaml.Grid.Cells;
  14. using Syncfusion.UI.Xaml.Grid.Helpers;
  15. using Syncfusion.UI.Xaml.ScrollAxis;
  16. using System;
  17. using System.Collections;
  18. using System.Collections.Generic;
  19. using System.Collections.ObjectModel;
  20. using System.ComponentModel;
  21. using System.Data;
  22. using System.Diagnostics.CodeAnalysis;
  23. using System.Linq;
  24. using System.Text;
  25. using System.Threading.Tasks;
  26. using System.Windows;
  27. using System.Windows.Controls;
  28. using System.Windows.Controls.Primitives;
  29. using System.Windows.Data;
  30. using System.Windows.Input;
  31. using System.Windows.Media;
  32. using System.Windows.Media.Effects;
  33. using System.Windows.Media.Imaging;
  34. using System.Windows.Threading;
  35. using Syncfusion.UI.Xaml.Grid.RowFilter;
  36. using Columns = InABox.Core.Columns;
  37. using DataColumn = System.Data.DataColumn;
  38. using DataRow = System.Data.DataRow;
  39. using TimeSpanEdit = Syncfusion.Windows.Shared.TimeSpanEdit;
  40. namespace InABox.DynamicGrid;
  41. public enum DynamicGridLines
  42. {
  43. Both,
  44. Horizontal,
  45. Vertical,
  46. None
  47. }
  48. public class DynamicGridGridUIComponent : IDynamicGridUIComponent, IDynamicGridGridUIComponent
  49. {
  50. private IDynamicGridUIComponentParent _parent = null!;
  51. public IDynamicGridUIComponentParent Parent
  52. {
  53. get => _parent;
  54. set
  55. {
  56. _parent = value;
  57. CellBackgroundConverter = new DynamicGridGridCellStyleConverter<System.Windows.Media.Brush?>(Parent, GetCellBackground);
  58. CellForegroundConverter = new DynamicGridGridCellStyleConverter<System.Windows.Media.Brush?>(Parent, GetCellForeground);
  59. CellFontSizeConverter = new DynamicGridGridCellStyleConverter<double?>(Parent, GetCellFontSize);
  60. CellFontStyleConverter = new DynamicGridGridCellStyleConverter<System.Windows.FontStyle?>(Parent, GetCellFontStyle);
  61. CellFontWeightConverter = new DynamicGridGridCellStyleConverter<System.Windows.FontWeight?>(Parent, GetCellFontWeight);
  62. DataGrid.RowStyleSelector = Parent.RowStyleSelector;
  63. DataGrid.TableSummaryRowStyleSelector = new SummaryRowStyleSelector(GetSummaryRowStyle);
  64. DataGrid.TableSummaryCellStyleSelector = new SummaryCellStyleSelector(this, GetSummaryCellStyle);
  65. }
  66. }
  67. FrameworkElement IDynamicGridUIComponent.Control => DataGrid;
  68. #region IDynamicGridGridUIComponent
  69. IList<DynamicColumnBase> IDynamicGridGridUIComponent.ColumnList => ColumnList;
  70. int IDynamicGridGridUIComponent.RowHeight => (int)RowHeight;
  71. #endregion
  72. protected readonly SfDataGrid DataGrid;
  73. private readonly ContextMenu ColumnsMenu;
  74. private readonly GridRowSizingOptions gridRowResizingOptions = new() { CanIncludeHiddenColumns = false, AutoFitMode = AutoFitMode.Default };
  75. /// <summary>
  76. /// <see langword="null"/> when <see cref="DataGrid.ItemsSource"/> is <see langword="null"/>, generally while the grid is refreshing its columns.
  77. /// </summary>
  78. protected DataTable? DataGridItems => (DataGrid.ItemsSource as DataTable);
  79. #region Configuration
  80. private DynamicGridLines _gridLines = DynamicGridLines.Both;
  81. public DynamicGridLines GridLines
  82. {
  83. get => _gridLines;
  84. set
  85. {
  86. _gridLines = value;
  87. DataGrid.GridLinesVisibility = value switch
  88. {
  89. DynamicGridLines.Both => GridLinesVisibility.Both,
  90. DynamicGridLines.Vertical => GridLinesVisibility.Vertical,
  91. DynamicGridLines.Horizontal => GridLinesVisibility.Horizontal,
  92. _ => GridLinesVisibility.None,
  93. };
  94. }
  95. }
  96. private bool _showHeader = false;
  97. public bool ShowHeader
  98. {
  99. get => _showHeader;
  100. set
  101. {
  102. _showHeader = value;
  103. DataGrid.HeaderRowHeight = value ? 30 : 0;
  104. }
  105. }
  106. public double RowHeight
  107. {
  108. get => DataGrid.RowHeight;
  109. set => DataGrid.RowHeight = value;
  110. }
  111. public double HeaderRowHeight
  112. {
  113. get => DataGrid.HeaderRowHeight;
  114. set => DataGrid.HeaderRowHeight = value;
  115. }
  116. #endregion
  117. public class GridFilterRowTextBoxRendererExt : GridFilterRowTextBoxRenderer
  118. {
  119. public override void OnInitializeDisplayElement(
  120. DataColumnBase dataColumn,
  121. TextBlock uiElement,
  122. object dataContext)
  123. {
  124. base.OnInitializeDisplayElement(dataColumn, uiElement, dataContext);
  125. object filterValue = dataColumn.GridColumn.FilteredFrom != FilteredFrom.FilterRow || dataColumn.GridColumn.FilterPredicates.Count <= 0
  126. ? (object) null
  127. : dataColumn.GridColumn.FilterPredicates.FirstOrDefault<FilterPredicate>().FilterValue;
  128. uiElement.Text = filterValue != null ? (string) filterValue : string.Empty;
  129. }
  130. }
  131. public static GridFilterRowTextBoxRendererExt? renderer = null;
  132. public DynamicGridGridUIComponent()
  133. {
  134. ColumnsMenu = new ContextMenu();
  135. ColumnsMenu.Opened += ColumnsMenu_ContextMenuOpening;
  136. DataGrid = new SfDataGrid();
  137. DataGrid.FilterRowCellRenderers.Add(nameof(GridFilterRowTextBoxRendererExt), new GridFilterRowTextBoxRendererExt());
  138. DataGrid.VerticalAlignment = VerticalAlignment.Stretch;
  139. DataGrid.HorizontalAlignment = HorizontalAlignment.Stretch;
  140. DataGrid.HeaderContextMenu = ColumnsMenu;
  141. DataGrid.CellTapped += DataGrid_CellTapped;
  142. DataGrid.CellDoubleTapped += DataGrid_CellDoubleTapped;
  143. DataGrid.SelectionChanging += DataGrid_SelectionChanging;
  144. DataGrid.SelectionChanged += DataGrid_SelectionChanged;
  145. DataGrid.SelectionMode = GridSelectionMode.Extended;
  146. DataGrid.SelectionUnit = GridSelectionUnit.Row;
  147. DataGrid.CanMaintainScrollPosition = true;
  148. DataGrid.SummaryCalculationUnit = SummaryCalculationUnit.AllRows;
  149. DataGrid.LiveDataUpdateMode = LiveDataUpdateMode.AllowSummaryUpdate;
  150. DataGrid.NavigationMode = NavigationMode.Row;
  151. DataGrid.AllowEditing = false;
  152. DataGrid.EditTrigger = EditTrigger.OnTap;
  153. DataGrid.BorderBrush = new SolidColorBrush(Colors.Gray);
  154. DataGrid.BorderThickness = new Thickness(0.75F);
  155. DataGrid.Background = new SolidColorBrush(Colors.DimGray);
  156. DataGrid.AutoGenerateColumns = false;
  157. DataGrid.ColumnSizer = GridLengthUnitType.AutoLastColumnFill;
  158. DataGrid.SelectionForegroundBrush = GetCellSelectionForegroundBrush() ?? DynamicGridUtils.SelectionForeground;
  159. DataGrid.RowSelectionBrush = GetCellSelectionBackgroundBrush() ?? DynamicGridUtils.SelectionBackground;
  160. DataGrid.AllowDraggingRows = false;
  161. DataGrid.Drop += DataGrid_Drop;
  162. DataGrid.DragOver += DataGrid_DragOver;
  163. DataGrid.RowDragDropTemplate = TemplateGenerator.CreateDataTemplate(() =>
  164. {
  165. // var border = new Border();
  166. // border.Width = 100;
  167. // border.Height = 100;
  168. // border.BorderBrush = new SolidColorBrush(Colors.Firebrick);
  169. // border.Background = new SolidColorBrush(Colors.Red);
  170. // border.CornerRadius = new CornerRadius(5);
  171. // return border;
  172. return null;
  173. });
  174. DataGrid.RowDropIndicatorMode = DropIndicatorMode.Line;
  175. DataGrid.RowDragDropController ??= new GridRowDragDropController();
  176. DataGrid.CurrentCellBorderThickness = new Thickness(0);
  177. DataGrid.EnableDataVirtualization = true;
  178. DataGrid.RowHeight = 30;
  179. DataGrid.QueryRowHeight += DataGrid_QueryRowHeight;
  180. DataGrid.HeaderRowHeight = 30;
  181. DataGrid.MouseLeftButtonUp += DataGrid_MouseLeftButtonUp;
  182. DataGrid.MouseRightButtonUp += DataGrid_MouseRightButtonUp;
  183. DataGrid.KeyUp += DataGrid_KeyUp;
  184. DataGrid.PreviewGotKeyboardFocus += DataGrid_PreviewGotKeyboardFocus;
  185. DataGrid.CurrentCellBeginEdit += DataGrid_CurrentCellBeginEdit;
  186. DataGrid.CurrentCellEndEdit += DataGrid_CurrentCellEndEdit;
  187. DataGrid.PreviewKeyUp += DataGrid_PreviewKeyUp;
  188. DataGrid.SetValue(ScrollViewer.VerticalScrollBarVisibilityProperty, ScrollBarVisibility.Visible);
  189. DataGrid.FilterChanged += DataGrid_FilterChanged;
  190. var fltstyle = new Style(typeof(GridFilterControl));
  191. fltstyle.Setters.Add(new Setter(GridFilterControl.FilterModeProperty, FilterMode.Both));
  192. fltstyle.Setters.Add(new Setter(GridFilterControl.SortOptionVisibilityProperty, Visibility.Collapsed));
  193. DataGrid.FilterPopupStyle = fltstyle;
  194. DataGrid.CellToolTipOpening += DataGrid_CellToolTipOpening;
  195. DataGrid.SizeChanged += DataGrid_SizeChanged;
  196. DataGrid.SelectionController = new GridSelectionControllerExt(DataGrid, this);
  197. }
  198. public class GridSelectionControllerExt(SfDataGrid datagrid, DynamicGridGridUIComponent grid) : GridSelectionController(datagrid)
  199. {
  200. public override bool HandleKeyDown(KeyEventArgs args)
  201. {
  202. if (args.Key == Key.Escape)
  203. {
  204. grid.CancelEdit();
  205. return false;
  206. }
  207. else
  208. {
  209. return base.HandleKeyDown(args);
  210. }
  211. }
  212. }
  213. #region Selection
  214. public CoreRow[] SelectedRows
  215. {
  216. get => GetSelectedRows();
  217. set => SetSelectedRows(value);
  218. }
  219. private CoreRow[] GetSelectedRows()
  220. {
  221. var result = new List<CoreRow>();
  222. foreach (var item in DataGrid.SelectedItems)
  223. {
  224. if (item is DataRowView datarow && GetRow(datarow.Row) is CoreRow row)
  225. {
  226. result.Add(row);
  227. }
  228. }
  229. return result.ToArray();
  230. }
  231. private void SetSelectedRows(CoreRow[] rows)
  232. {
  233. DataGrid.SelectedItems.Clear();
  234. var table = DataGridItems;
  235. if(table is null) return;
  236. var dataRows = rows.Select(x => _rowMap.FirstOrDefault(y => x == y.Value).Key);
  237. if (!Parent.Options.MultiSelect)
  238. {
  239. dataRows = dataRows.Take(1);
  240. }
  241. foreach (var row in dataRows)
  242. {
  243. var record = DataGrid.View?.Records.FirstOrDefault(x => (x.Data as DataRowView)!.Row == row);
  244. if(record?.Data is DataRowView rowView)
  245. {
  246. DataGrid.SelectedItems.Add(rowView);
  247. }
  248. }
  249. }
  250. private void DataGrid_SelectionChanging(object? sender, Syncfusion.UI.Xaml.Grid.GridSelectionChangingEventArgs e)
  251. {
  252. var cancel = new CancelEventArgs();
  253. Parent.BeforeSelection(cancel);
  254. if (cancel.Cancel)
  255. {
  256. e.Cancel = true;
  257. }
  258. }
  259. private void DataGrid_SelectionChanged(object? sender, GridSelectionChangedEventArgs e)
  260. {
  261. if(Parent.IsReady && !Parent.IsRefreshing)
  262. {
  263. StartTimer();
  264. }
  265. }
  266. private DispatcherTimer? clicktimer;
  267. private void StartTimer()
  268. {
  269. if (clicktimer is null)
  270. {
  271. clicktimer = new DispatcherTimer();
  272. clicktimer.Interval = TimeSpan.FromMilliseconds(200);
  273. clicktimer.Tick += (o, e) =>
  274. {
  275. clicktimer.IsEnabled = false;
  276. Parent.SelectItems(SelectedRows);
  277. };
  278. }
  279. clicktimer.IsEnabled = true;
  280. }
  281. private void StopTimer()
  282. {
  283. if (clicktimer is not null)
  284. clicktimer.IsEnabled = false;
  285. }
  286. #endregion
  287. #region Rows
  288. public CoreRow[] GetVisibleRows()
  289. {
  290. var items = DataGrid.ItemsSource;
  291. var result = new List<CoreRow>();
  292. var table = DataGridItems;
  293. if (table is null) return Array.Empty<CoreRow>();
  294. var rows = DataGrid.View.Records.Select(x => (x.Data as DataRowView)!).ToList();
  295. foreach (var row in rows)
  296. {
  297. if(GetRow(row.Row) is CoreRow coreRow)
  298. {
  299. result.Add(coreRow);
  300. }
  301. }
  302. return result.ToArray();
  303. }
  304. // Please always use this function where possible!
  305. /// <summary>
  306. /// Get the <see cref="CoreRow"/> associated with a <paramref name="rowIndex"/> given from the Syncfusion DataGrid.
  307. /// </summary>
  308. /// <remarks>
  309. /// This is mandatory to use whenever we want the data associated with an index which Syncfusion has given us,
  310. /// because filtering and sorting will cause normal indexing operations to fail.
  311. /// </remarks>
  312. /// <param name="rowIndex"></param>
  313. /// <returns></returns>
  314. protected CoreRow? GetRowFromIndex(int rowIndex)
  315. {
  316. // Syncfusion has given us the row index, so it also will give us the correct row, after sorting.
  317. // Hence, here we use the syncfusion DataGrid.GetRecordAtRowIndex, which *should* always return a DataRowView.
  318. var row = DataGrid.GetRecordAtRowIndex(rowIndex);
  319. if (row is not DataRowView dataRowView || DataGridItems is not DataTable table)
  320. return null;
  321. return GetRow(dataRowView.Row);
  322. }
  323. private CoreRow? GetRow(DataRow row)
  324. {
  325. return _rowMap.GetValueOrDefault(row);
  326. }
  327. #endregion
  328. #region Input
  329. private bool bFilterVisible;
  330. private void DataGrid_MouseRightButtonUp(object sender, MouseButtonEventArgs e)
  331. {
  332. if (!DataGrid.IsEnabled)
  333. return;
  334. var visualContainer = DataGrid.GetVisualContainer();
  335. var rowcolumnindex = visualContainer.PointToCellRowColumnIndex(e.GetPosition(visualContainer));
  336. var columnindex = DataGrid.ResolveToGridVisibleColumnIndex(rowcolumnindex.ColumnIndex);
  337. var column = GetColumn(columnindex);
  338. if(column is not null)
  339. {
  340. Parent.OpenColumnMenu(column);
  341. }
  342. }
  343. private void DataGrid_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
  344. {
  345. if (!DataGrid.IsEnabled)
  346. return;
  347. var visualContainer = DataGrid.GetVisualContainer();
  348. var rowcolumnindex = visualContainer.PointToCellRowColumnIndex(e.GetPosition(visualContainer));
  349. var columnindex = DataGrid.ResolveToGridVisibleColumnIndex(rowcolumnindex.ColumnIndex);
  350. // Header Click Here!
  351. if (rowcolumnindex.RowIndex < DataGrid.StackedHeaderRows.Count + 1)
  352. {
  353. var column = GetColumn(columnindex);
  354. if(column is DynamicActionColumn dac)
  355. {
  356. Parent.ExecuteActionColumn(dac, null);
  357. }
  358. }
  359. else if (!bFilterVisible)
  360. {
  361. StartTimer();
  362. }
  363. }
  364. private void DataGrid_CellTapped(object? sender, GridCellTappedEventArgs e)
  365. {
  366. if (!DataGrid.IsEnabled)
  367. return;
  368. if (GetColumn(e.RowColumnIndex.ColumnIndex) is DynamicActionColumn dac)
  369. {
  370. if(e.ChangedButton == MouseButton.Left || (e.ChangedButton == MouseButton.Right && dac is DynamicMenuColumn))
  371. {
  372. Parent.ExecuteActionColumn(dac, SelectedRows);
  373. }
  374. }
  375. else
  376. {
  377. StartTimer();
  378. }
  379. }
  380. private void DataGrid_KeyUp(object sender, KeyEventArgs e)
  381. {
  382. if (sender != DataGrid) return;
  383. Parent.HandleKey(e);
  384. }
  385. private void DataGrid_PreviewGotKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
  386. {
  387. var bOld = bFilterVisible;
  388. if (e.NewFocus is GridFilterControl)
  389. bFilterVisible = true;
  390. else if (e.NewFocus is ScrollViewer || e.NewFocus is SfDataGrid)
  391. bFilterVisible = false;
  392. if (bOld && !bFilterVisible)
  393. {
  394. Parent.SelectItems(SelectedRows);
  395. }
  396. }
  397. private void DataGrid_CellDoubleTapped(object? sender, GridCellDoubleTappedEventArgs e)
  398. {
  399. StopTimer();
  400. Parent.DoubleClickCell(GetRowFromIndex(e.RowColumnIndex.RowIndex), GetColumn(e.RowColumnIndex.ColumnIndex));
  401. }
  402. private void DataGrid_QueryRowHeight(object? sender, QueryRowHeightEventArgs e)
  403. {
  404. if (e.RowIndex > 0)
  405. {
  406. e.Height = DataGrid.RowHeight;
  407. if (DataGrid.GridColumnSizer.GetAutoRowHeight(e.RowIndex, gridRowResizingOptions, out var autoHeight))
  408. if (autoHeight > DataGrid.RowHeight)
  409. e.Height = autoHeight;
  410. e.Handled = true;
  411. }
  412. }
  413. #endregion
  414. #region UI Stuff
  415. private void ColumnsMenu_ContextMenuOpening(object sender, RoutedEventArgs e)
  416. {
  417. if (sender is not ContextMenu menu) return;
  418. menu.Items.Clear();
  419. Parent.LoadColumnsMenu(menu);
  420. }
  421. private void DataGrid_SizeChanged(object sender, SizeChangedEventArgs e)
  422. {
  423. if (Parent.IsReady && !Parent.IsRefreshing)
  424. ResizeColumns(DataGrid, e.NewSize.Width - 2, e.NewSize.Height - 2);
  425. }
  426. private void UpdateRecordCount()
  427. {
  428. var count = DataGrid.View != null ? DataGrid.View.Records.Count : Parent.Data.Rows.Count;
  429. Parent.UpdateRecordCount(count);
  430. }
  431. private void DataGrid_CellToolTipOpening(object? sender, GridCellToolTipOpeningEventArgs e)
  432. {
  433. var column = GetColumn(e.RowColumnIndex.ColumnIndex);
  434. if (column is DynamicActionColumn ac)
  435. {
  436. var toolTip = ac.ToolTip;
  437. if (toolTip is null)
  438. return;
  439. var row = GetRowFromIndex(e.RowColumnIndex.RowIndex);
  440. e.ToolTip.Template = TemplateGenerator.CreateControlTemplate(
  441. typeof(ToolTip),
  442. () => toolTip.Invoke(ac, row)
  443. );
  444. }
  445. else if(column is DynamicGridColumn gc)
  446. {
  447. e.ToolTip.Content = gc.Editor.ToolTip;
  448. }
  449. }
  450. public void ScrollIntoView(CoreRow row)
  451. {
  452. var rowIdx = DataGrid.ResolveToRowIndex(row.Index + 1);
  453. DataGrid.ScrollInView(new RowColumnIndex(rowIdx, 0));
  454. }
  455. int IDynamicGridUIComponent.DesiredWidth()
  456. {
  457. return this.DesiredWidth();
  458. }
  459. public bool OptionsChanged()
  460. {
  461. ColumnsMenu.Visibility = Parent.Options.SelectColumns ? Visibility.Visible : Visibility.Hidden;
  462. var allowEditing = Parent.IsDirectEditMode();
  463. var reloadColumns = false;
  464. if (DataGrid.AllowEditing != allowEditing)
  465. {
  466. DataGrid.NavigationMode = allowEditing ? NavigationMode.Cell : NavigationMode.Row;
  467. DataGrid.AllowEditing = allowEditing;
  468. reloadColumns = true;
  469. }
  470. DataGrid.FilterRowPosition = Parent.Options.FilterRows && Parent.CanFilter() ? FilterRowPosition.FixedTop : FilterRowPosition.None;
  471. if (Parent.Options.DragSource || Parent.Options.ReorderRows)
  472. {
  473. if (!DataGrid.AllowDraggingRows)
  474. {
  475. DataGrid.AllowDraggingRows = true;
  476. DataGrid.RowDragDropController.DragStart += RowDragDropController_DragStart;
  477. DataGrid.RowDragDropController.DragOver += RowDragDropController_DragOver;
  478. }
  479. }
  480. else
  481. {
  482. if (DataGrid.AllowDraggingRows)
  483. {
  484. DataGrid.AllowDraggingRows = false;
  485. DataGrid.RowDragDropController.DragStart -= RowDragDropController_DragStart;
  486. DataGrid.RowDragDropController.DragOver -= RowDragDropController_DragOver;
  487. }
  488. }
  489. if (Parent.Options.DragTarget || Parent.Options.ReorderRows)
  490. {
  491. if (!DataGrid.AllowDrop)
  492. {
  493. DataGrid.AllowDrop = true;
  494. DataGrid.RowDragDropController.Drop += RowDragDropController_Drop;
  495. DataGrid.RowDragDropController.Dropped += RowDragDropController_Dropped;
  496. }
  497. }
  498. else
  499. {
  500. if (DataGrid.AllowDrop)
  501. {
  502. DataGrid.AllowDrop = false;
  503. DataGrid.RowDragDropController.Drop -= RowDragDropController_Drop;
  504. DataGrid.RowDragDropController.Dropped -= RowDragDropController_Dropped;
  505. }
  506. }
  507. DataGrid.SelectionMode = Parent.Options.MultiSelect ? GridSelectionMode.Extended : GridSelectionMode.Single;
  508. return reloadColumns && DataGrid.Columns.Count > 0;
  509. }
  510. #endregion
  511. #region Filter Predicates
  512. private readonly Dictionary<string, string> _filterpredicates = new();
  513. public void AddVisualFilter(string column, string value, FilterType filtertype = FilterType.Contains)
  514. {
  515. if (string.IsNullOrWhiteSpace(value))
  516. return;
  517. var col = DataGrid.Columns.FirstOrDefault((x=>String.Equals(x.MappingName?.ToUpper(),column?.Replace(".", "_").ToUpper())));
  518. if (col != null)
  519. {
  520. col.FilterPredicates.Add(new FilterPredicate { FilterType = filtertype, FilterValue = value });
  521. col.FilteredFrom = FilteredFrom.FilterRow;
  522. }
  523. }
  524. public List<Tuple<string, Func<CoreRow, bool>>> GetFilterPredicates()
  525. {
  526. var list = new List<Tuple<string, Func<CoreRow, bool>>>();
  527. foreach (var column in DataGrid.Columns)
  528. {
  529. var colIndex = DataGrid.Columns.IndexOf(column);
  530. var col = ColumnList[colIndex];
  531. var filter = Parent.GetColumnFilter(col);
  532. if (col is DynamicGridColumn gridColumn)
  533. {
  534. var rowPredicate = DynamicGridGridUIComponentExtension.ConvertColumnPredicates(gridColumn, column.FilterPredicates);
  535. if(filter is not null)
  536. {
  537. var oldPred = rowPredicate;
  538. if(oldPred is not null)
  539. {
  540. rowPredicate = row => oldPred(row) && filter.FilterRow(row);
  541. }
  542. else
  543. {
  544. rowPredicate = filter.FilterRow;
  545. }
  546. }
  547. if(rowPredicate is not null)
  548. {
  549. list.Add(new(gridColumn.ColumnName, rowPredicate));
  550. }
  551. }
  552. else if(col is DynamicActionColumn dac)
  553. {
  554. if(filter is not null)
  555. {
  556. list.Add(new(column.MappingName, filter.FilterRow));
  557. }
  558. }
  559. }
  560. return list;
  561. }
  562. private void DataGrid_FilterChanged(object? o, GridFilterEventArgs e)
  563. {
  564. if (e.FilterPredicates == null)
  565. {
  566. if (_filterpredicates.ContainsKey(e.Column.MappingName))
  567. _filterpredicates.Remove(e.Column.MappingName);
  568. }
  569. else
  570. {
  571. _filterpredicates[e.Column.MappingName] = Serialization.Serialize(e.FilterPredicates, true);
  572. }
  573. Parent.UIFilterChanged(this);
  574. UpdateRecordCount();
  575. }
  576. #endregion
  577. #region Styles
  578. private DynamicGridGridCellStyleConverter<System.Windows.Media.Brush?> CellBackgroundConverter = null!;
  579. private DynamicGridGridCellStyleConverter<System.Windows.Media.Brush?> CellForegroundConverter = null!;
  580. private DynamicGridGridCellStyleConverter<double?> CellFontSizeConverter = null!;
  581. private DynamicGridGridCellStyleConverter<System.Windows.FontStyle?> CellFontStyleConverter = null!;
  582. private DynamicGridGridCellStyleConverter<System.Windows.FontWeight?> CellFontWeightConverter = null!;
  583. protected virtual Brush? GetCellSelectionForegroundBrush() => DynamicGridUtils.SelectionForeground;
  584. protected virtual Brush? GetCellSelectionBackgroundBrush() => DynamicGridUtils.SelectionBackground;
  585. protected virtual Brush? GetCellBackground(CoreRow row, DynamicColumnBase column) => null;
  586. protected virtual Brush? GetCellForeground(CoreRow row, DynamicColumnBase column) => null;
  587. protected virtual double? GetCellFontSize(CoreRow row, DynamicColumnBase column) => null;
  588. protected virtual FontStyle? GetCellFontStyle(CoreRow row, DynamicColumnBase column) => null;
  589. protected virtual FontWeight? GetCellFontWeight(CoreRow row, DynamicColumnBase column) => null;
  590. protected virtual Style GetCellStyle(DynamicColumnBase column)
  591. {
  592. var style = new Style(typeof(GridCell));
  593. return style;
  594. }
  595. protected virtual Style GetHeaderCellStyle(DynamicColumnBase column)
  596. {
  597. var headStyle = new Style(typeof(GridHeaderCellControl));
  598. headStyle.Setters.Add(new Setter(Control.BackgroundProperty, new SolidColorBrush(Colors.Gainsboro)));
  599. headStyle.Setters.Add(new Setter(Control.ForegroundProperty, new SolidColorBrush(Colors.Black)));
  600. headStyle.Setters.Add(new Setter(Control.FontSizeProperty, 12D));
  601. if (column is DynamicActionColumn actionColumn)
  602. {
  603. headStyle.Setters.Add(new Setter(Control.BorderThicknessProperty, new Thickness(0.0)));
  604. headStyle.Setters.Add(new Setter(Control.MarginProperty, new Thickness(0, 0, 1, 1)));
  605. if (column is DynamicImageColumn imgCol)
  606. {
  607. if (imgCol.HeaderText.IsNullOrWhiteSpace())
  608. {
  609. var image = imgCol.Image?.Invoke(null);
  610. if (image != null)
  611. {
  612. headStyle.AddSetter(GridHeaderCellControl.PaddingProperty, new Thickness(4.0));
  613. headStyle.AddSetter(GridHeaderCellControl.ContentTemplateProperty,
  614. TemplateGenerator.CreateDataTemplate(() =>
  615. {
  616. return new Image { Source = image };
  617. }));
  618. }
  619. }
  620. }
  621. if (actionColumn.VerticalHeader && !actionColumn.HeaderText.IsNullOrWhiteSpace())
  622. {
  623. headStyle.Setters.Add(new Setter(Control.HorizontalContentAlignmentProperty, HorizontalAlignment.Left));
  624. headStyle.Setters.Add(new Setter(Control.TemplateProperty,
  625. Application.Current.Resources["VerticalColumnHeader"] as ControlTemplate));
  626. }
  627. }
  628. return headStyle;
  629. }
  630. protected virtual Style GetColumnGroupHeaderCellStyle(DynamicGridColumnGroup group)
  631. {
  632. var headstyle = new Style(typeof(GridStackedHeaderCellControl));
  633. headstyle.Setters.Add(new Setter(Control.BackgroundProperty, new SolidColorBrush(Colors.Gainsboro)));
  634. headstyle.Setters.Add(new Setter(Control.ForegroundProperty, new SolidColorBrush(Colors.Black)));
  635. headstyle.Setters.Add(new Setter(Control.FontSizeProperty, 12D));
  636. headstyle.Setters.Add(new Setter(Control.BorderThicknessProperty, new Thickness(0.0, 0.0, 0, 0)));
  637. headstyle.Setters.Add(new Setter(Control.MarginProperty, new Thickness(0, 0, 1, 1)));
  638. return headstyle;
  639. }
  640. protected virtual Style GetSummaryRowStyle()
  641. {
  642. var style = new Style(typeof(TableSummaryRowControl));
  643. return style;
  644. }
  645. protected virtual Style GetSummaryCellStyle(DynamicColumnBase column)
  646. {
  647. var style = new Style(typeof(GridTableSummaryCell));
  648. style.Setters.Add(new Setter(Control.BackgroundProperty, new SolidColorBrush(Colors.Gainsboro)));
  649. style.Setters.Add(new Setter(Control.ForegroundProperty, new SolidColorBrush(Colors.Black)));
  650. if(column is DynamicGridColumn gridColumn)
  651. {
  652. style.Setters.Add(new Setter(Control.HorizontalContentAlignmentProperty,
  653. column != null ? gridColumn.HorizontalAlignment(typeof(double)) : HorizontalAlignment.Right));
  654. }
  655. else if(column is DynamicTextColumn textColumn)
  656. {
  657. style.Setters.Add(new Setter(Control.HorizontalContentAlignmentProperty, textColumn.Alignment.HorizontalAlignment(typeof(string))));
  658. }
  659. else
  660. {
  661. style.Setters.Add(new Setter(Control.HorizontalContentAlignmentProperty, HorizontalAlignment.Right));
  662. }
  663. style.Setters.Add(new Setter(Control.BorderBrushProperty, new SolidColorBrush(Colors.Gray)));
  664. style.Setters.Add(new Setter(Control.BorderThicknessProperty, new Thickness(0, 0, 0.75, 0)));
  665. style.Setters.Add(new Setter(Control.FontSizeProperty, 12D));
  666. style.Setters.Add(new Setter(Control.FontWeightProperty, FontWeights.DemiBold));
  667. return style;
  668. }
  669. private void AddCellStyleConverters(Style cellstyle, DynamicColumnBase column, string sColName)
  670. {
  671. cellstyle.Setters.Add(new Setter(Control.BackgroundProperty,
  672. WPFUtils.CreateMultiBinding(
  673. CellBackgroundConverter.WrapConverter(x => x[0]),
  674. parameter: new DynamicGridCellStyleParameters(column, DependencyProperty.UnsetValue))
  675. .AddBinding(new Binding("."))
  676. .AddBinding(new Binding(sColName))));
  677. cellstyle.Setters.Add(new Setter(Control.ForegroundProperty,
  678. WPFUtils.CreateMultiBinding(
  679. CellForegroundConverter.WrapConverter(x => x[0]),
  680. parameter: new DynamicGridCellStyleParameters(column, DependencyProperty.UnsetValue))
  681. .AddBinding(new Binding("."))
  682. .AddBinding(new Binding(sColName))));
  683. cellstyle.Setters.Add(new Setter(Control.FontSizeProperty,
  684. WPFUtils.CreateMultiBinding(
  685. CellFontSizeConverter.WrapConverter(x => x[0]),
  686. parameter: new DynamicGridCellStyleParameters(column, DependencyProperty.UnsetValue))
  687. .AddBinding(new Binding("."))
  688. .AddBinding(new Binding(sColName))));
  689. cellstyle.Setters.Add(new Setter(Control.FontStyleProperty,
  690. WPFUtils.CreateMultiBinding(
  691. CellFontStyleConverter.WrapConverter(x => x[0]),
  692. parameter: new DynamicGridCellStyleParameters(column, DependencyProperty.UnsetValue))
  693. .AddBinding(new Binding("."))
  694. .AddBinding(new Binding(sColName))));
  695. cellstyle.Setters.Add(new Setter(Control.FontWeightProperty,
  696. WPFUtils.CreateMultiBinding(
  697. CellFontWeightConverter.WrapConverter(x => x[0]),
  698. parameter: new DynamicGridCellStyleParameters(column, DependencyProperty.UnsetValue))
  699. .AddBinding(new Binding("."))
  700. .AddBinding(new Binding(sColName))));
  701. }
  702. #endregion
  703. #region Columns
  704. protected readonly List<DynamicColumnBase> ColumnList = new();
  705. private List<DynamicActionColumn> ActionColumns = new();
  706. protected DynamicColumnBase? GetColumn(int index) =>
  707. index >= 0 && index < ColumnList.Count ? ColumnList[index] : null;
  708. #region Column Grouping
  709. private class StackedHeaderRenderer(DynamicGridGridUIComponent grid) : GridStackedHeaderCellRenderer
  710. {
  711. public override void OnInitializeEditElement(DataColumnBase dataColumn, GridStackedHeaderCellControl uiElement, object dataContext)
  712. {
  713. if(dataContext is StackedColumn column && grid.ColumnGroupMap.TryGetValue(column.MappingName, out var group))
  714. {
  715. uiElement.Style = grid.GetColumnGroupHeaderCellStyle(group);
  716. }
  717. base.OnInitializeEditElement(dataColumn, uiElement, dataContext);
  718. }
  719. }
  720. private Dictionary<string, DynamicGridColumnGroup> ColumnGroupMap = new();
  721. private void LoadStackedHeaders(DynamicGridColumnGroupings groupings)
  722. {
  723. DataGrid.StackedHeaderRows.Clear();
  724. ColumnGroupMap.Clear();
  725. var j = 0;
  726. foreach(var grouping in groupings)
  727. {
  728. var row = new StackedHeaderRow();
  729. var i = 0;
  730. foreach(var group in grouping.Groups)
  731. {
  732. var start = Math.Max(i, ColumnList.IndexOf(group.StartColumn));
  733. var end = Math.Max(start, ColumnList.IndexOf(group.EndColumn));
  734. if(end < start)
  735. {
  736. i = end + 1;
  737. continue;
  738. }
  739. var cols = Enumerable.Range(start, end - start + 1).Select(i => DataGrid.Columns[i]).ToArray();
  740. var name = $"_GroupColumn{j}";
  741. var stackedColumn = new StackedColumn
  742. {
  743. HeaderText = group.Header,
  744. ChildColumns = string.Join(',', cols.Select(x => x.MappingName)),
  745. MappingName = name
  746. };
  747. ColumnGroupMap.Add(name, group);
  748. j = j + 1;
  749. row.StackedColumns.Add(stackedColumn);
  750. i = end + 1;
  751. }
  752. DataGrid.StackedHeaderRows.Add(row);
  753. }
  754. if(groupings.Count > 0)
  755. {
  756. DataGrid.CellRenderers.Remove("StackedHeader");
  757. DataGrid.CellRenderers.Add("StackedHeader", new StackedHeaderRenderer(this));
  758. }
  759. }
  760. #endregion
  761. private void ResizeColumns(SfDataGrid grid, double width, double height)
  762. {
  763. if (Parent.Data == null || width <= 0)
  764. return;
  765. grid.Dispatcher.BeginInvoke(() =>
  766. {
  767. foreach (var (index, size) in this.CalculateColumnSizes(width))
  768. DataGrid.Columns[index].Width = Math.Max(0.0F, size);
  769. });
  770. }
  771. #region Column Filtering
  772. private void ApplyFilterStyle(GridColumn column, bool filtering, bool allowSorting)
  773. {
  774. var filterRowCellStyle = new Style();
  775. if (filtering)
  776. {
  777. filterRowCellStyle.Setters.Add(new Setter(Control.BackgroundProperty, DynamicGridUtils.FilterBackground));
  778. column.ImmediateUpdateColumnFilter = true;
  779. column.ColumnFilter = ColumnFilter.Value;
  780. column.FilterRowCondition = FilterRowCondition.Contains;
  781. column.FilterRowOptionsVisibility = Visibility.Collapsed;
  782. column.AllowBlankFilters = true;
  783. column.AllowSorting = allowSorting && Parent.CanSort();
  784. }
  785. else
  786. {
  787. filterRowCellStyle.Setters.Add(new Setter(Control.BackgroundProperty, new SolidColorBrush(Colors.Gainsboro)));
  788. filterRowCellStyle.Setters.Add(new Setter(UIElement.IsEnabledProperty, false));
  789. column.ColumnFilter = ColumnFilter.Value;
  790. column.AllowSorting = false;
  791. column.FilterRowEditorType = "TextBox";
  792. column.FilterRowOptionsVisibility = Visibility.Collapsed;
  793. }
  794. column.FilterRowCellStyle = filterRowCellStyle;
  795. }
  796. private void Filter_FilterChanged(IDynamicGridColumnFilter filter)
  797. {
  798. AddRows(Parent.Data.Rows, true);
  799. Parent.UIFilterChanged(this);
  800. }
  801. private bool FilterRow(CoreRow row)
  802. {
  803. foreach(var column in ColumnList)
  804. {
  805. if(Parent.GetColumnFilter(column) is IDynamicGridColumnFilter filter && !filter.FilterRow(row))
  806. {
  807. return false;
  808. }
  809. }
  810. return true;
  811. }
  812. private void SetFilterUIButton(GridColumn gridColumn, DynamicColumnBase column)
  813. {
  814. if (!Parent.Options.FilterRows || !Parent.CanFilter()) return;
  815. if (Parent.GetColumnFilter(column) is not IDynamicGridColumnFilter filter) return;
  816. var vertical = column is DynamicActionColumn ac && ac.VerticalHeader && !ac.HeaderText.IsNullOrWhiteSpace();
  817. var horizontalAlignment = gridColumn.HorizontalHeaderContentAlignment;
  818. gridColumn.HorizontalHeaderContentAlignment = HorizontalAlignment.Stretch;
  819. gridColumn.HeaderTemplate = TemplateGenerator.CreateDataTemplate(() =>
  820. {
  821. var grid = new Grid();
  822. grid.AddColumn(GridUnitType.Star);
  823. var filterCol = grid.AddColumn(GridUnitType.Auto);
  824. var content = new ContentControl();
  825. content.HorizontalAlignment = horizontalAlignment;
  826. content.VerticalAlignment = VerticalAlignment.Center;
  827. content.SetBinding(ContentControl.ContentProperty, new Binding());
  828. grid.AddChild(content, 0, 0);
  829. var button = new DynamicGridColumnFilterUIButton(filter);
  830. grid.AddChild(button, 0, 1);
  831. if(vertical)
  832. {
  833. button.LayoutTransform = new RotateTransform(90);
  834. content.HorizontalAlignment = HorizontalAlignment.Stretch;
  835. }
  836. return grid;
  837. });
  838. }
  839. #endregion
  840. #region Summaries
  841. private readonly ObservableCollection<ISummaryColumn> Summaries = new();
  842. public class SummaryRowStyleSelector(Func<Style> selector) : StyleSelector
  843. {
  844. public override Style? SelectStyle(object item, DependencyObject container)
  845. {
  846. return selector();
  847. }
  848. }
  849. public class SummaryCellStyleSelector(DynamicGridGridUIComponent parent, Func<DynamicColumnBase, Style> selector) : StyleSelector
  850. {
  851. public override Style? SelectStyle(object item, DependencyObject container)
  852. {
  853. var vcol = ((GridTableSummaryCell)container).ColumnBase.ColumnIndex;
  854. var col = parent.GetColumn(vcol);
  855. return col is not null ? selector(col) : null;
  856. }
  857. }
  858. private GridSummaryColumn? ConvertSummary(IDynamicGridSummary? summary)
  859. {
  860. if(summary is DynamicGridSumSummary sum)
  861. {
  862. var newSummary = new GridSummaryColumn
  863. {
  864. Format = $"{{Sum:{sum.Format}}}"
  865. };
  866. if(sum.AggregateType == typeof(double))
  867. {
  868. newSummary.SummaryType = Syncfusion.Data.SummaryType.DoubleAggregate;
  869. }
  870. else if(sum.AggregateType == typeof(int))
  871. {
  872. newSummary.SummaryType = Syncfusion.Data.SummaryType.Int32Aggregate;
  873. }
  874. else if(sum.AggregateType == typeof(TimeSpan))
  875. {
  876. newSummary.SummaryType = Syncfusion.Data.SummaryType.Custom;
  877. newSummary.CustomAggregate = new DynamicGridDurationAggregate();
  878. }
  879. return newSummary;
  880. }
  881. else if(summary is DynamicGridCountSummary count)
  882. {
  883. return new GridSummaryColumn
  884. {
  885. Format = "{Count:N0}",
  886. SummaryType = Syncfusion.Data.SummaryType.CountAggregate
  887. };
  888. }
  889. else if(summary is DynamicGridCustomSummary custom)
  890. {
  891. return new GridSummaryColumn
  892. {
  893. Format = $"{{Sum:{custom.Format}}}",
  894. SummaryType = SummaryType.Custom,
  895. CustomAggregate = new InternalAggregate(this, custom.Aggregate)
  896. };
  897. }
  898. else if(summary is DynamicGridTemplateSummary template)
  899. {
  900. return new GridSummaryColumn
  901. {
  902. TemplateSelector = new FuncTemplateSelector((item, o) => template.Template())
  903. };
  904. }
  905. else
  906. {
  907. return null;
  908. }
  909. }
  910. private class InternalAggregate(DynamicGridGridUIComponent grid, DynamicGridCustomSummary.AggregateFunc aggregate) : ISummaryAggregate
  911. {
  912. public object? Sum { get; set; } = null;
  913. public Action<IEnumerable, string, PropertyDescriptor> CalculateAggregateFunc() => CalculateAggregate;
  914. private void CalculateAggregate(IEnumerable items, string property, PropertyDescriptor args)
  915. {
  916. if (items is IEnumerable<DataRowView> rows)
  917. {
  918. Sum = aggregate(rows.Select(x =>
  919. {
  920. return grid.GetRow(x.Row);
  921. }).NotNull());
  922. }
  923. else
  924. {
  925. Logger.Send(LogType.Error, "", $"Attempting to calculate aggregate on invalid data type '{items.GetType()}'.");
  926. }
  927. }
  928. }
  929. private void LoadSummaries()
  930. {
  931. if (Summaries.Any())
  932. {
  933. DataGrid.CellRenderers.Remove("TableSummary");
  934. DataGrid.CellRenderers.Add("TableSummary", new DynamicGridAggregateRenderer());
  935. DataGrid.TableSummaryRows.Add(new GridTableSummaryRow
  936. {
  937. ShowSummaryInRow = false,
  938. Position = TableSummaryRowPosition.Bottom,
  939. SummaryColumns = Summaries,
  940. });
  941. }
  942. }
  943. #endregion
  944. private void LoadActionColumn(DynamicActionColumn column)
  945. {
  946. var i = ActionColumns.Count;
  947. var sColName = string.Format("ActionColumn{0}", i);
  948. ActionColumns.Add(column);
  949. gridRowResizingOptions.ExcludeColumns.Add(sColName);
  950. var summary = ConvertSummary(column.Summary());
  951. if (summary != null)
  952. {
  953. summary.Name = sColName;
  954. summary.MappingName = sColName;
  955. Summaries.Add(summary);
  956. }
  957. if (column is DynamicImageColumn imgcol)
  958. {
  959. var newcol = new GridImageColumn();
  960. newcol.MappingName = sColName;
  961. newcol.Width = column.Width == 0 ? DataGrid.RowHeight : column.Width;
  962. newcol.Padding = new Thickness(4);
  963. newcol.ImageHeight = DataGrid.RowHeight - 8;
  964. newcol.ImageWidth = DataGrid.RowHeight - 8;
  965. newcol.ColumnSizer = GridLengthUnitType.None;
  966. newcol.HeaderText = column.HeaderText;
  967. newcol.AllowEditing = false;
  968. ApplyFilterStyle(newcol, true, false);
  969. SetFilterUIButton(newcol, column);
  970. newcol.ShowToolTip = column.ToolTip != null;
  971. newcol.ShowHeaderToolTip = column.ToolTip != null;
  972. var style = new Style();
  973. style.Setters.Add(new Setter(Control.BackgroundProperty, new SolidColorBrush(Colors.Gainsboro)));
  974. style.Setters.Add(new Setter(Control.IsEnabledProperty, false));
  975. newcol.FilterRowCellStyle = style;
  976. newcol.HeaderStyle = GetHeaderCellStyle(column);
  977. var cellstyle = GetCellStyle(column);
  978. AddCellStyleConverters(cellstyle, column, sColName);
  979. newcol.CellStyle = cellstyle;
  980. DataGrid.Columns.Add(newcol);
  981. ColumnList.Add(column);
  982. }
  983. else if (column is DynamicTextColumn txtCol)
  984. {
  985. var newcol = new GridTextColumn();
  986. gridRowResizingOptions.ExcludeColumns.Add(sColName);
  987. newcol.TextWrapping = TextWrapping.NoWrap;
  988. newcol.TextAlignment = txtCol.Alignment.TextAlignment(typeof(string));
  989. newcol.AllowEditing = false;
  990. newcol.UpdateTrigger = UpdateSourceTrigger.PropertyChanged;
  991. newcol.MappingName = sColName;
  992. newcol.Width = column.Width;
  993. newcol.ColumnSizer = GridLengthUnitType.None;
  994. newcol.HeaderText = column.HeaderText;
  995. newcol.AllowSorting = false;
  996. newcol.FilterRowOptionsVisibility = Visibility.Collapsed;
  997. newcol.ShowHeaderToolTip = column.ToolTip != null;
  998. newcol.ShowToolTip = column.ToolTip != null;
  999. newcol.ShowHeaderToolTip = column.ToolTip != null;
  1000. ApplyFilterStyle(newcol, true, true);
  1001. SetFilterUIButton(newcol, column);
  1002. newcol.HeaderStyle = GetHeaderCellStyle(column);
  1003. var cellstyle = GetCellStyle(column);
  1004. AddCellStyleConverters(cellstyle, column, sColName);
  1005. newcol.CellStyle = cellstyle;
  1006. DataGrid.Columns.Add(newcol);
  1007. ColumnList.Add(column);
  1008. }
  1009. else if (column is DynamicTemplateColumn tmplCol)
  1010. {
  1011. var newcol = new GridTemplateColumn();
  1012. newcol.CellTemplate = TemplateGenerator.CreateDataTemplate(() =>
  1013. {
  1014. var content = new ContentControl();
  1015. content.SetBinding(ContentControl.ContentProperty,
  1016. WPFUtils.CreateMultiBinding(new MultiFuncConverter(x =>
  1017. {
  1018. if(x[0] is DataRowView view && DataGridItems is DataTable table && GetRow(view.Row) is CoreRow row)
  1019. {
  1020. return tmplCol.Template(row);
  1021. }
  1022. return null;
  1023. }))
  1024. .AddBinding(new Binding("."))
  1025. .AddBinding(new Binding(sColName)));
  1026. return content;
  1027. });
  1028. newcol.AllowEditing = false;
  1029. newcol.UpdateTrigger = UpdateSourceTrigger.PropertyChanged;
  1030. newcol.MappingName = sColName;
  1031. newcol.Width = tmplCol.Width;
  1032. newcol.ColumnSizer = GridLengthUnitType.None;
  1033. newcol.HeaderText = column.HeaderText;
  1034. newcol.AllowSorting = false;
  1035. newcol.FilterRowOptionsVisibility = Visibility.Collapsed;
  1036. newcol.ShowToolTip = column.ToolTip != null;
  1037. newcol.ShowHeaderToolTip = column.ToolTip != null;
  1038. SetFilterUIButton(newcol, column);
  1039. var style = new Style();
  1040. style.Setters.Add(new Setter(Control.BackgroundProperty, new SolidColorBrush(Colors.Gainsboro)));
  1041. style.Setters.Add(new Setter(Control.IsEnabledProperty, false));
  1042. newcol.FilterRowCellStyle = style;
  1043. newcol.HeaderStyle = GetHeaderCellStyle(column);
  1044. var cellstyle = GetCellStyle(column);
  1045. AddCellStyleConverters(cellstyle, column, sColName);
  1046. newcol.CellStyle = cellstyle;
  1047. DataGrid.Columns.Add(newcol);
  1048. ColumnList.Add(column);
  1049. }
  1050. }
  1051. protected virtual bool CreateEditorColumn(DynamicGridColumn column, [NotNullWhen(true)] out IDynamicGridEditorColumn? newColumn)
  1052. {
  1053. return (this as IDynamicGridGridUIComponent).CreateEditorColumn(column, out newColumn);
  1054. }
  1055. protected virtual void ConfigureColumn(DynamicGridColumn column, IDynamicGridEditorColumn newColumn)
  1056. {
  1057. }
  1058. private void LoadDataColumn(DynamicGridColumn column)
  1059. {
  1060. column.Editor = Parent.CustomiseEditor(column, column.Editor);
  1061. if (this.CreateEditorColumn(column, out var newcol))
  1062. {
  1063. if (!newcol.VariableHeight)
  1064. gridRowResizingOptions.ExcludeColumns.Add(newcol.MappingName);
  1065. var newColumn = newcol.CreateGridColumn();
  1066. newColumn.FilterRowEditorType = nameof(GridFilterRowTextBoxRendererExt);
  1067. var summary = ConvertSummary(newcol.Summary());
  1068. if (summary != null)
  1069. {
  1070. summary.Name = newcol.MappingName;
  1071. summary.MappingName = newcol.MappingName;
  1072. Summaries.Add(summary);
  1073. }
  1074. ApplyFilterStyle(newColumn, newcol.Filtered, true);
  1075. newColumn.HeaderStyle = GetHeaderCellStyle(column);
  1076. SetFilterUIButton(newColumn, column);
  1077. newColumn.ShowHeaderToolTip = !column.Editor.ToolTip.IsNullOrWhiteSpace();
  1078. var cellstyle = GetCellStyle(column);
  1079. if (Parent.IsDirectEditMode())
  1080. {
  1081. if (column.Editor is null || !newcol.Editable || !column.Editor.Editable.IsDirectEditable())
  1082. {
  1083. cellstyle.Setters.Add(new Setter(Control.BackgroundProperty,
  1084. new Binding()
  1085. {
  1086. Path = new PropertyPath("."), Converter = CellBackgroundConverter,
  1087. ConverterParameter = new DynamicGridCellStyleParameters(column,new SolidColorBrush(Colors.WhiteSmoke))
  1088. }));
  1089. newColumn.AllowEditing = false;
  1090. }
  1091. else
  1092. {
  1093. cellstyle.Setters.Add(new Setter(Control.BackgroundProperty,
  1094. new Binding()
  1095. {
  1096. Path = new PropertyPath("."), Converter = CellBackgroundConverter,
  1097. ConverterParameter = new DynamicGridCellStyleParameters(column,new SolidColorBrush(Colors.LightYellow))
  1098. }));
  1099. newColumn.AllowEditing = true;
  1100. }
  1101. cellstyle.Setters.Add(new Setter(Control.ForegroundProperty, new SolidColorBrush(Colors.Black)));
  1102. newColumn.CellStyle = cellstyle;
  1103. }
  1104. else
  1105. {
  1106. AddCellStyleConverters(cellstyle, column, newColumn.MappingName);
  1107. newColumn.CellStyle = cellstyle;
  1108. }
  1109. ConfigureColumn(column, newcol);
  1110. DataGrid.Columns.Add(newColumn);
  1111. ColumnList.Add(column);
  1112. }
  1113. }
  1114. public void RefreshColumns(IEnumerable<DynamicColumnBase> columns, DynamicGridColumnGroupings groupings)
  1115. {
  1116. if (DataGrid.View != null)
  1117. DataGrid.View.Filter = null;
  1118. DataGrid.ItemsSource = null;
  1119. DataGrid.Columns.Suspend();
  1120. ColumnList.Clear();
  1121. ActionColumns.Clear();
  1122. DataGrid.Columns.Clear();
  1123. DataGrid.TableSummaryRows.Clear();
  1124. gridRowResizingOptions.ExcludeColumns = new List<string>();
  1125. Summaries.Clear();
  1126. foreach(var column in columns)
  1127. {
  1128. if(Parent.GetColumnFilter(column) is IDynamicGridColumnFilter filter)
  1129. {
  1130. filter.FilterChanged += Filter_FilterChanged;
  1131. }
  1132. if(column is DynamicActionColumn ac)
  1133. {
  1134. LoadActionColumn(ac);
  1135. }
  1136. else if(column is DynamicGridColumn gc)
  1137. {
  1138. LoadDataColumn(gc);
  1139. }
  1140. }
  1141. LoadSummaries();
  1142. LoadStackedHeaders(groupings);
  1143. DataGrid.Columns.Resume();
  1144. DataGrid.RefreshColumns();
  1145. foreach (var key in _filterpredicates.Keys.ToArray())
  1146. if (DataGrid.Columns.Any(x => string.Equals(x.MappingName, key)))
  1147. {
  1148. var predicates = Serialization.Deserialize<List<FilterPredicate>>(_filterpredicates[key]);
  1149. if(predicates is not null)
  1150. {
  1151. foreach (var predicate in predicates)
  1152. {
  1153. DataGrid.Columns[key].FilterPredicates.Add(predicate);
  1154. DataGrid.Columns[key].FilteredFrom = FilteredFrom.FilterRow;
  1155. }
  1156. }
  1157. }
  1158. else
  1159. {
  1160. _filterpredicates.Remove(key);
  1161. }
  1162. ResizeColumns(DataGrid, DataGrid.ActualWidth - 2, DataGrid.ActualHeight - 2);
  1163. if(groupings.Count > 0)
  1164. {
  1165. // THis here is to fix a problem with Syncfusion when we have stackedHeaderRows; the above setting of the ItemsSource to null
  1166. // was causing the resetting of it to fail when reloading, due to some internal OutOfRange Exception. THe use case was selecting columns on the
  1167. // Stock Forecast grid.
  1168. RefreshData(new CoreTable());
  1169. }
  1170. if (DataGrid.View != null)
  1171. DataGrid.View.Filter = (o) =>
  1172. {
  1173. return true;
  1174. };
  1175. }
  1176. #endregion
  1177. #region Data
  1178. protected bool _invalidating = false;
  1179. private Dictionary<DataRow, CoreRow> _rowMap = new();
  1180. public void BeforeRefresh()
  1181. {
  1182. DataGrid.SelectionForegroundBrush = GetCellSelectionForegroundBrush();
  1183. DataGrid.RowSelectionBrush = GetCellSelectionBackgroundBrush();
  1184. }
  1185. public void RefreshData(CoreTable data)
  1186. {
  1187. var result = new DataTable();
  1188. _rowMap.Clear();
  1189. var defaults = new List<object?>();
  1190. foreach (var column in data.Columns)
  1191. {
  1192. var colname = column.ColumnName.Replace('.', '_');
  1193. if (!result.Columns.Contains(colname))
  1194. {
  1195. result.Columns.Add(colname, column.DataType);
  1196. if (!Parent.IsDirectEditMode())
  1197. defaults.Add(column.DataType.GetDefault());
  1198. }
  1199. }
  1200. for (var i = 0; i < ActionColumns.Count; i++)
  1201. result.Columns.Add(string.Format("ActionColumn{0}", i),
  1202. ActionColumns[i] is DynamicImageColumn
  1203. ? typeof(ImageSource)
  1204. : typeof(String)
  1205. );
  1206. foreach (var row in data.Rows.Where(FilterRow))
  1207. {
  1208. var newrow = result.NewRow();
  1209. CoreRowToDataRow(newrow, row, defaults);
  1210. result.Rows.Add(newrow);
  1211. _rowMap[newrow] = row;
  1212. }
  1213. result.ColumnChanged += Result_ColumnChanged;
  1214. //int rowIndex = DataGrid.SelectionController.CurrentCellManager.CurrentRowColumnIndex.RowIndex;
  1215. //int columnIndex = DataGrid.SelectionController.CurrentCellManager.CurrentRowColumnIndex.ColumnIndex;
  1216. //int scrollRowIndex = DataGrid.GetVisualContainer().ScrollRows.LastBodyVisibleLineIndex;
  1217. //this.DataGrid.ScrollInView(new Syncfusion.UI.Xaml.ScrollAxis.RowColumnIndex(scrollRowIndex, columnIndex));
  1218. DataGrid.ItemsSource = result;
  1219. ResizeColumns(DataGrid, DataGrid.ActualWidth - 1, DataGrid.ActualHeight);
  1220. UpdateRecordCount();
  1221. }
  1222. private void AddRows(IEnumerable<CoreRow> rows, bool clearRows)
  1223. {
  1224. var table = DataGridItems;
  1225. if(table is null)
  1226. {
  1227. return;
  1228. }
  1229. _invalidating = true;
  1230. if (clearRows)
  1231. {
  1232. table.Rows.Clear();
  1233. _rowMap.Clear();
  1234. }
  1235. var defaults = new List<object?>();
  1236. if (!Parent.IsDirectEditMode())
  1237. foreach (var column in table.Columns.Cast<DataColumn>())
  1238. {
  1239. defaults.Add(column.DataType.GetDefault());
  1240. }
  1241. foreach(var row in rows.Where(FilterRow))
  1242. {
  1243. var newRow = table.NewRow();
  1244. CoreRowToDataRow(newRow, row, defaults);
  1245. table.Rows.Add(newRow);
  1246. _rowMap[newRow] = row;
  1247. }
  1248. UpdateRecordCount();
  1249. _invalidating = false;
  1250. }
  1251. public void AddPage(IEnumerable<CoreRow> page)
  1252. {
  1253. AddRows(page, false);
  1254. }
  1255. public void InvalidateRow(CoreRow row)
  1256. {
  1257. var table = DataGridItems;
  1258. if(table is null)
  1259. {
  1260. return;
  1261. }
  1262. _invalidating = true;
  1263. var rowdata = new List<object?>(row.Values);
  1264. foreach (var ac in ActionColumns)
  1265. rowdata.Add(ac.Data(row));
  1266. var datarow = table.Rows[row.Index];
  1267. for (var i = 0; i < rowdata.Count; i++)
  1268. datarow[i] = rowdata[i] ?? DBNull.Value;
  1269. _invalidating = false;
  1270. }
  1271. private void CoreRowToDataRow(DataRow newrow, CoreRow row, List<object?> defaults)
  1272. {
  1273. var rowdata = new List<object?>(row.Values);
  1274. foreach (var ac in ActionColumns)
  1275. rowdata.Add(ac.Data(row));
  1276. try
  1277. {
  1278. var data = ProcessRow(rowdata, defaults).ToArray();
  1279. newrow.ItemArray = data;
  1280. }
  1281. catch (Exception)
  1282. {
  1283. throw;
  1284. }
  1285. }
  1286. private static IEnumerable<object?> ProcessRow(List<object?> values, List<object?> defaults)
  1287. {
  1288. if (defaults == null || defaults.Count == 0)
  1289. return values;
  1290. return values.WithIndex().Select(x =>
  1291. {
  1292. var (i, value) = x;
  1293. var defaultvalue = i < defaults.Count ? defaults[i] : null;
  1294. return value is null || (value.Equals(defaultvalue) && !value.GetType().IsEnum) ? null : value;
  1295. });
  1296. }
  1297. #endregion
  1298. #region Direct Edit
  1299. protected bool bChanged;
  1300. protected class DirectEditingObject
  1301. {
  1302. public object? Object { get; set; }
  1303. public CoreRow Row { get; set; }
  1304. public DataRow? DataRow { get; set; }
  1305. public DirectEditingObject(object? obj, CoreRow row, DataRow? dataRow)
  1306. {
  1307. Object = obj;
  1308. Row = row;
  1309. DataRow = dataRow;
  1310. }
  1311. }
  1312. protected DirectEditingObject? _editingObject;
  1313. protected DirectEditingObject EnsureEditingObject(CoreRow row)
  1314. {
  1315. _editingObject ??= new(GetEditingObject(row), row, DataGridItems?.Rows[row.Index]);
  1316. return _editingObject;
  1317. }
  1318. protected virtual object? GetEditingObject(CoreRow row)
  1319. {
  1320. return null;
  1321. }
  1322. private DataRow? GetDataRow(CoreRow row)
  1323. {
  1324. return DataGridItems?.Rows[row.Index];
  1325. }
  1326. void IDynamicGridUIComponent.UpdateCell(CoreRow row, string column, object? value)
  1327. {
  1328. var dataRow = GetDataRow(row);
  1329. var datacolname = column.Replace(".", "_");
  1330. if(dataRow is not null)
  1331. {
  1332. dataRow[datacolname] = value ?? DBNull.Value;
  1333. }
  1334. }
  1335. void IDynamicGridUIComponent.UpdateCell(CoreRow row, DynamicColumnBase column)
  1336. {
  1337. var dataRow = GetDataRow(row);
  1338. if(dataRow is not null)
  1339. {
  1340. if(column is DynamicGridColumn gc)
  1341. {
  1342. var dataColName = gc.ColumnName.Replace(".", "_");
  1343. dataRow[dataColName] = row[gc.ColumnName] ?? DBNull.Value;
  1344. }
  1345. else if(column is DynamicActionColumn ac)
  1346. {
  1347. var i = ActionColumns.IndexOf(ac);
  1348. dataRow[$"ActionColumn{i}"] = ac.Data(row);
  1349. }
  1350. }
  1351. }
  1352. protected void UpdateRow(CoreRow row, DataRow dataRow)
  1353. {
  1354. foreach(var (key, value) in row)
  1355. {
  1356. var datacolname = key.Replace(".", "_");
  1357. var dataValue = dataRow[datacolname];
  1358. if (!Equals(dataValue, value) && !(value is null && dataValue == DBNull.Value))
  1359. {
  1360. dataRow[datacolname] = value ?? DBNull.Value;
  1361. }
  1362. }
  1363. for (var i = 0; i < ActionColumns.Count; i++)
  1364. dataRow[$"ActionColumn{i}"] = ActionColumns[i].Data(row);
  1365. }
  1366. void IDynamicGridUIComponent.UpdateRow(CoreRow row)
  1367. {
  1368. var dataRow = GetDataRow(row);
  1369. if(dataRow is not null)
  1370. {
  1371. UpdateRow(row, dataRow);
  1372. }
  1373. }
  1374. protected virtual void DoEntityChanged(IDynamicColumnBase column, DynamicColumnEntityChangedEventArgs args)
  1375. {
  1376. }
  1377. protected virtual void BeginEdit(CoreRow row, CurrentCellBeginEditEventArgs e)
  1378. {
  1379. EnsureEditingObject(row);
  1380. }
  1381. private void DataGrid_CurrentCellBeginEdit(object? sender, CurrentCellBeginEditEventArgs e)
  1382. {
  1383. var row = GetRowFromIndex(e.RowColumnIndex.RowIndex);
  1384. if (row is null)
  1385. return;
  1386. BeginEdit(row, e);
  1387. bChanged = false;
  1388. }
  1389. protected virtual void UpdateData(string column, Dictionary<CoreColumn, object?> updates)
  1390. {
  1391. if (_editingObject is null) return;
  1392. var coreRow = _editingObject.Row;
  1393. Parent.UpdateData(coreRow, column, updates);
  1394. }
  1395. private void UpdateData(int rowIndex, int columnIndex)
  1396. {
  1397. var table = DataGridItems;
  1398. if (table is null)
  1399. return;
  1400. if (GetColumn(columnIndex) is DynamicGridColumn gridcol)
  1401. {
  1402. var datacol = Parent.Data.Columns.FirstOrDefault(x => x.ColumnName.Equals(gridcol.ColumnName));
  1403. if (datacol != null)
  1404. {
  1405. var datacolindex = Parent.Data.Columns.IndexOf(datacol);
  1406. var value = table.Rows[rowIndex][datacolindex];
  1407. if (value is DBNull)
  1408. value = CoreUtils.GetDefault(datacol.DataType);
  1409. UpdateData(datacol.ColumnName, new Dictionary<CoreColumn, object?>() { { datacol, value } });
  1410. }
  1411. }
  1412. }
  1413. protected virtual void ColumnChanged(CoreColumn dataCol, CoreRow row, object? value)
  1414. {
  1415. var col = ColumnList.OfType<DynamicGridColumn>()
  1416. .FirstOrDefault(x => x.ColumnName.Equals(dataCol.ColumnName));
  1417. if (col is null)
  1418. return;
  1419. if (col.Editor is CheckBoxEditor)
  1420. {
  1421. EnsureEditingObject(row);
  1422. if(_editingObject is not null)
  1423. {
  1424. if (value is DBNull)
  1425. value = CoreUtils.GetDefault(dataCol.DataType);
  1426. _invalidating = true;
  1427. UpdateData(dataCol.ColumnName, new Dictionary<CoreColumn, object?>() { { dataCol, value } });
  1428. _invalidating = false;
  1429. }
  1430. _editingObject = null;
  1431. }
  1432. if (_editingObject is not null)
  1433. bChanged = true;
  1434. }
  1435. private void DataGrid_CurrentCellEndEdit(object? sender, CurrentCellEndEditEventArgs e)
  1436. {
  1437. if (_editingObject is not null && bChanged)
  1438. {
  1439. UpdateData(_editingObject.Row.Index, e.RowColumnIndex.ColumnIndex);
  1440. }
  1441. if (bChanged)
  1442. Parent.DoChanged();
  1443. bChanged = false;
  1444. _editingObject = null;
  1445. // Commented out on 19/02/2024 by Kenric. I don't see this being necessary, though I could be wrong. Nevertheless, it was causing a bug when
  1446. // editing the filter row. It seems that this causes Syncfusion to commit the filter predicates internally, which means that after leaving a
  1447. // filter row cell, the filter remained even once it was cleared, meaning a refresh was necessary to get the data back.
  1448. // I've tested on Bills to see if editing works with this empty, and it seems so.
  1449. //DataGridItems?.AcceptChanges();
  1450. }
  1451. private void DataGrid_PreviewKeyUp(object sender, KeyEventArgs e)
  1452. {
  1453. if (e.Key == Key.OemPeriod)
  1454. {
  1455. if (e.OriginalSource is TimeSpanEdit editor && editor.SelectionStart < 2)
  1456. {
  1457. editor.SelectionStart = 3;
  1458. }
  1459. }
  1460. else if (e.Key == Key.Tab)
  1461. {
  1462. if (Parent.IsDirectEditMode())
  1463. {
  1464. DataGrid.SelectionController.CurrentCellManager.EndEdit();
  1465. DataGrid.MoveFocus(new TraversalRequest(FocusNavigationDirection.Right));
  1466. DataGrid.SelectionController.CurrentCellManager.BeginEdit();
  1467. e.Handled = true;
  1468. }
  1469. }
  1470. else if(e.Key == Key.Escape)
  1471. {
  1472. if (Parent.IsDirectEditMode())
  1473. {
  1474. bChanged = false;
  1475. }
  1476. }
  1477. }
  1478. protected virtual void CancelEdit()
  1479. {
  1480. var obj = _editingObject;
  1481. bChanged = false;
  1482. _editingObject = null;
  1483. DataGrid.SelectionController.CurrentCellManager.EndEdit(false);
  1484. if(obj is not null && obj.DataRow is not null)
  1485. {
  1486. UpdateRow(obj.Row, obj.DataRow);
  1487. }
  1488. }
  1489. private void Result_ColumnChanged(object sender, DataColumnChangeEventArgs e)
  1490. {
  1491. if (_invalidating) return;
  1492. if (sender is not DataTable table) return;
  1493. var row = GetRow(e.Row);
  1494. if (row is null)
  1495. return;
  1496. var colIdx = table.Columns.IndexOf(e.Column);
  1497. if (colIdx < 0 || colIdx >= Parent.Data.Columns.Count)
  1498. return;
  1499. var dataCol = Parent.Data.Columns[colIdx];
  1500. var value = e.Row[e.Column!];
  1501. ColumnChanged(dataCol, row, value);
  1502. }
  1503. #endregion
  1504. #region Drag + Drop
  1505. private void DataGrid_DragOver(object sender, DragEventArgs e)
  1506. {
  1507. if (!Parent.Options.DragTarget)
  1508. {
  1509. return;
  1510. }
  1511. Parent.DragOver(sender, e);
  1512. }
  1513. private void DataGrid_Drop(object sender, DragEventArgs e)
  1514. {
  1515. if (!Parent.Options.DragTarget)
  1516. {
  1517. return;
  1518. }
  1519. Parent.Drop(sender, e);
  1520. }
  1521. private void RowDragDropController_DragStart(object? sender, GridRowDragStartEventArgs e)
  1522. {
  1523. var rows = e.DraggingRecords.Select(record =>
  1524. {
  1525. var rowIndex = DataGrid.ResolveToRowIndex(record);
  1526. return GetRowFromIndex(rowIndex);
  1527. }).NotNull().ToArray();
  1528. Parent.DragStart(sender, rows);
  1529. }
  1530. private void RowDragDropController_Drop(object? sender, GridRowDropEventArgs e)
  1531. {
  1532. if (!Parent.Options.ReorderRows)
  1533. {
  1534. e.Handled = true;
  1535. }
  1536. e.Handled = true;
  1537. }
  1538. private void RowDragDropController_Dropped(object? sender, GridRowDroppedEventArgs e)
  1539. {
  1540. if (!Parent.Options.ReorderRows)
  1541. {
  1542. }
  1543. if(e.DropPosition != DropPosition.None)
  1544. {
  1545. var records = (e.Data.GetData("Records") as ObservableCollection<object>)!;
  1546. var targetIdx = (int)e.TargetRecord;
  1547. var rows = records.Select(x =>
  1548. {
  1549. if (x is DataRowView dataRow)
  1550. {
  1551. return GetRow(dataRow.Row);
  1552. }
  1553. else
  1554. {
  1555. return null;
  1556. }
  1557. }).NotNull().OrderBy(x => x.Index).ToArray();
  1558. Parent.MoveRows(rows, e.DropPosition == DropPosition.DropBelow ? targetIdx + 1 : targetIdx);
  1559. }
  1560. }
  1561. private void RowDragDropController_DragOver(object? sender, GridRowDragOverEventArgs e)
  1562. {
  1563. if (!Parent.Options.ReorderRows)
  1564. {
  1565. e.Handled = true;
  1566. }
  1567. }
  1568. #endregion
  1569. }
  1570. public class DynamicGridGridUIComponent<T> : DynamicGridGridUIComponent, IDynamicGridUIComponent<T>
  1571. where T : BaseObject, new()
  1572. {
  1573. private Dictionary<string, CoreTable> Lookups = new();
  1574. public new IDynamicGridUIComponentParent<T> Parent
  1575. {
  1576. get => (IDynamicGridUIComponentParent<T>)base.Parent;
  1577. set => base.Parent = value;
  1578. }
  1579. public DynamicGridGridUIComponent()
  1580. {
  1581. DataGrid.CurrentCellDropDownSelectionChanged += DataGrid_CurrentCellDropDownSelectionChanged;
  1582. }
  1583. protected override bool CreateEditorColumn(DynamicGridColumn column, [NotNullWhen(true)] out IDynamicGridEditorColumn? newColumn)
  1584. {
  1585. if((this as IDynamicGridGridUIComponent).CreateEditorColumn<T>(column, out newColumn))
  1586. {
  1587. if(newColumn is IDynamicGridEditorColumn<T> typed)
  1588. {
  1589. typed.GetEntity = () => _editingObject?.Object as T;
  1590. typed.EntityChanged += DoEntityChanged;
  1591. }
  1592. return true;
  1593. }
  1594. else
  1595. {
  1596. return false;
  1597. }
  1598. }
  1599. protected override void ConfigureColumn(DynamicGridColumn column, IDynamicGridEditorColumn newColumn)
  1600. {
  1601. base.ConfigureColumn(column, newColumn);
  1602. foreach (var extra in newColumn.ExtraColumns)
  1603. Parent.AddHiddenColumn(extra);
  1604. }
  1605. #region Direct Edit
  1606. protected override object? GetEditingObject(CoreRow row)
  1607. {
  1608. return Parent.LoadItem(row);
  1609. }
  1610. private DataRow? GetDataRow(CoreRow row)
  1611. {
  1612. return DataGridItems?.Rows[row.Index];
  1613. }
  1614. protected override void DoEntityChanged(IDynamicColumnBase column, DynamicColumnEntityChangedEventArgs args)
  1615. {
  1616. base.DoEntityChanged(column, args);
  1617. if (_editingObject?.Object is not T obj) return;
  1618. Parent.EntityChanged(obj, _editingObject.Row, args.ColumnName, args.Changes);
  1619. }
  1620. protected override void UpdateData(string column, Dictionary<CoreColumn, object?> updates)
  1621. {
  1622. if (_editingObject?.Object is not T obj) return;
  1623. var coreRow = _editingObject.Row;
  1624. Parent.UpdateData(obj, coreRow, column, updates);
  1625. }
  1626. private void DataGrid_CurrentCellDropDownSelectionChanged(object? sender,
  1627. CurrentCellDropDownSelectionChangedEventArgs e)
  1628. {
  1629. var row = GetRowFromIndex(e.RowColumnIndex.RowIndex);
  1630. if (row is null)
  1631. return;
  1632. EnsureEditingObject(row);
  1633. if ((_editingObject is not null) && (e.SelectedItem is Tuple<object?, string> tuple))
  1634. {
  1635. var mappedname = DataGrid.Columns[e.RowColumnIndex.ColumnIndex].MappingName;
  1636. var colno = DataGridItems!.Columns.IndexOf(mappedname);
  1637. var corecol = Parent.Data.Columns[colno].ColumnName;
  1638. var updates = new Dictionary<CoreColumn, object?>();
  1639. var dotIdx = corecol.LastIndexOf('.');
  1640. string prefix, field;
  1641. if(dotIdx == -1)
  1642. {
  1643. prefix = "";
  1644. field = corecol;
  1645. }
  1646. else
  1647. {
  1648. prefix = corecol[..dotIdx];
  1649. field = corecol[(dotIdx + 1)..];
  1650. }
  1651. var col = ColumnList.OfType<DynamicGridColumn>()
  1652. .FirstOrDefault(x => x.ColumnName.Equals(corecol));
  1653. if (col?.Editor is ILookupEditor editor)
  1654. {
  1655. var data = editor.Values(corecol);
  1656. var lookuprow = data.Rows.FirstOrDefault(r => Equals(r[field], tuple.Item1))
  1657. ?? data.NewRow(true);
  1658. foreach (CoreColumn lookupcol in data.Columns)
  1659. {
  1660. var columnname = String.IsNullOrWhiteSpace(prefix)
  1661. ? lookupcol.ColumnName
  1662. : String.Join(".", prefix, lookupcol.ColumnName);
  1663. var updatecol = Parent.Data.Columns.FirstOrDefault(x => String.Equals(x.ColumnName, columnname));
  1664. if (updatecol != null)
  1665. updates[updatecol] = lookuprow[lookupcol.ColumnName];
  1666. }
  1667. UpdateData(corecol, updates);
  1668. bChanged = true;
  1669. }
  1670. }
  1671. }
  1672. protected override void BeginEdit(CoreRow row, CurrentCellBeginEditEventArgs e)
  1673. {
  1674. base.BeginEdit(row, e);
  1675. var table = DataGridItems;
  1676. if (table is null) return;
  1677. var column = DataGrid.Columns[e.RowColumnIndex.ColumnIndex] as GridComboBoxColumn;
  1678. if (column != null && column.ItemsSource == null)
  1679. {
  1680. var colname = column.MappingName;
  1681. var colno = table.Columns.IndexOf(colname);
  1682. var property = Parent.Data.Columns[colno].ColumnName;
  1683. var col = ColumnList.OfType<DynamicGridColumn>()
  1684. .FirstOrDefault(x => x.ColumnName.Equals(property));
  1685. if (col?.Editor is ILookupEditor lookupEditor)
  1686. {
  1687. if (!Lookups.ContainsKey(property))
  1688. Lookups[property] = lookupEditor.Values(property);
  1689. var combo = column;
  1690. combo.ItemsSource = Lookups[property].ToDictionary(Lookups[property].Columns[0].ColumnName, "Display");
  1691. combo.SelectedValuePath = "Key";
  1692. combo.DisplayMemberPath = "Value";
  1693. }
  1694. }
  1695. }
  1696. #endregion
  1697. }