DynamicGridGridUIComponent.cs 68 KB

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