DynamicGridGridUIComponent.cs 70 KB

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