DynamicGridGridUIComponent.cs 67 KB

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