DynamicGridGridUIComponent.cs 68 KB

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