DynamicGridGridUIComponent.cs 66 KB

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