DynamicGridGridUIComponent.cs 65 KB

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