DynamicGridGridUIComponent.cs 68 KB

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