DynamicGridGridUIComponent.cs 64 KB

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