DynamicGridGridUIComponent.cs 68 KB

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