DynamicGridGridUIComponent.cs 66 KB

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