DynamicGridGridUIComponent.cs 67 KB

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