DynamicGridGridUIComponent.cs 66 KB

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