DynamicGridGridUIComponent.cs 68 KB

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