DynamicGridGridUIComponent.cs 67 KB

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