DynamicGridGridUIComponent.cs 64 KB

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