DynamicGridGridUIComponent.cs 68 KB

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