DynamicGridGridUIComponent.cs 67 KB

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