DynamicGridGridUIComponent.cs 66 KB

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