DynamicGridGridUIComponent.cs 60 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537
  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. private 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.HasOption(DynamicGridOption.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 == 0)
  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.HasOption(DynamicGridOption.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.HasOption(DynamicGridOption.FilterRows);
  415. DataGrid.FilterRowPosition = Parent.HasOption(DynamicGridOption.FilterRows) ? FilterRowPosition.FixedTop : FilterRowPosition.None;
  416. if (Parent.HasOption(DynamicGridOption.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.HasOption(DynamicGridOption.DragTarget);
  433. DataGrid.SelectionMode = Parent.HasOption(DynamicGridOption.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 col = DataGrid.Columns.IndexOf(e.Column);
  476. if (GetColumn(col) is DynamicActionColumn column && column.Filters is not null)
  477. e.ItemsSource = column.Filters.Select(x => new FilterElement
  478. { DisplayText = x, ActualValue = x, IsSelected = column.SelectedFilters is null || column.SelectedFilters.Contains(x) });
  479. }
  480. private void DataGrid_CellToolTipOpening(object? sender, GridCellToolTipOpeningEventArgs e)
  481. {
  482. if (GetColumn(e.RowColumnIndex.ColumnIndex) is not DynamicActionColumn col)
  483. return;
  484. var toolTip = col.ToolTip;
  485. if (toolTip is null)
  486. return;
  487. var row = GetRowFromIndex(e.RowColumnIndex.RowIndex);
  488. e.ToolTip.Template = TemplateGenerator.CreateControlTemplate(
  489. typeof(ToolTip),
  490. () => toolTip.Invoke(col, row)
  491. );
  492. }
  493. public void AddVisualFilter(string column, string value, FilterType filtertype = FilterType.Contains)
  494. {
  495. if (string.IsNullOrWhiteSpace(value))
  496. return;
  497. var col = DataGrid.Columns.FirstOrDefault((x=>String.Equals(x.MappingName?.ToUpper(),column?.Replace(".", "_").ToUpper())));
  498. if (col != null)
  499. {
  500. col.FilterPredicates.Add(new FilterPredicate { FilterType = filtertype, FilterValue = value });
  501. col.FilteredFrom = FilteredFrom.FilterRow;
  502. }
  503. }
  504. public List<Tuple<string, Func<CoreRow, bool>>> GetFilterPredicates()
  505. {
  506. var list = new List<Tuple<string, Func<CoreRow, bool>>>();
  507. foreach (var column in DataGrid.Columns)
  508. {
  509. var colIndex = DataGrid.Columns.IndexOf(column);
  510. var col = ColumnList[colIndex];
  511. if (col is DynamicGridColumn gridColumn)
  512. {
  513. var rowPredicate = DynamicGridGridUIComponentExtension.ConvertColumnPredicates(gridColumn, column.FilterPredicates);
  514. if(rowPredicate is not null)
  515. {
  516. list.Add(new(gridColumn.ColumnName, rowPredicate));
  517. }
  518. }
  519. }
  520. return list;
  521. }
  522. public void ScrollIntoView(CoreRow row)
  523. {
  524. var rowIdx = DataGrid.ResolveToRowIndex(row.Index + 1);
  525. DataGrid.ScrollInView(new RowColumnIndex(rowIdx, 0));
  526. }
  527. protected virtual Brush? GetCellSelectionForegroundBrush() => DynamicGridUtils.SelectionForeground;
  528. protected virtual Brush? GetCellSelectionBackgroundBrush() => DynamicGridUtils.SelectionBackground;
  529. protected virtual Brush? GetCellBackground(CoreRow row, DynamicColumnBase column) => null;
  530. protected virtual Brush? GetCellForeground(CoreRow row, DynamicColumnBase column) => null;
  531. protected virtual double? GetCellFontSize(CoreRow row, DynamicColumnBase column) => null;
  532. protected virtual FontStyle? GetCellFontStyle(CoreRow row, DynamicColumnBase column) => null;
  533. protected virtual FontWeight? GetCellFontWeight(CoreRow row, DynamicColumnBase column) => null;
  534. #region Columns
  535. private class StackedHeaderRenderer : GridStackedHeaderCellRenderer
  536. {
  537. private Style Style;
  538. public StackedHeaderRenderer()
  539. {
  540. var headstyle = new Style(typeof(GridStackedHeaderCellControl));
  541. headstyle.Setters.Add(new Setter(Control.BackgroundProperty, new SolidColorBrush(Colors.Gainsboro)));
  542. headstyle.Setters.Add(new Setter(Control.ForegroundProperty, new SolidColorBrush(Colors.Black)));
  543. headstyle.Setters.Add(new Setter(Control.FontSizeProperty, 12D));
  544. headstyle.Setters.Add(new Setter(Control.BorderThicknessProperty, new Thickness(0.0, 0.0, 0, 0)));
  545. headstyle.Setters.Add(new Setter(Control.MarginProperty, new Thickness(0, 0, 1, 1)));
  546. Style = headstyle;
  547. }
  548. public override void OnInitializeEditElement(DataColumnBase dataColumn, GridStackedHeaderCellControl uiElement, object dataContext)
  549. {
  550. uiElement.Style = Style;
  551. base.OnInitializeEditElement(dataColumn, uiElement, dataContext);
  552. }
  553. }
  554. private void LoadStackedHeaders(DynamicGridColumnGroupings groupings)
  555. {
  556. DataGrid.StackedHeaderRows.Clear();
  557. foreach(var grouping in groupings)
  558. {
  559. var row = new StackedHeaderRow();
  560. var i = 0;
  561. foreach(var group in grouping.Groups)
  562. {
  563. var start = Math.Max(i, ColumnList.IndexOf(group.StartColumn));
  564. var end = Math.Max(start, ColumnList.IndexOf(group.EndColumn));
  565. if(end < start)
  566. {
  567. i = end + 1;
  568. continue;
  569. }
  570. var cols = Enumerable.Range(start, end - start + 1).Select(i => DataGrid.Columns[i]).ToArray();
  571. var stackedColumn = new StackedColumn
  572. {
  573. HeaderText = group.Header,
  574. ChildColumns = string.Join(',', cols.Select(x => x.MappingName))
  575. };
  576. row.StackedColumns.Add(stackedColumn);
  577. i = end + 1;
  578. }
  579. DataGrid.StackedHeaderRows.Add(row);
  580. }
  581. if(groupings.Count > 0)
  582. {
  583. DataGrid.CellRenderers.Remove("StackedHeader");
  584. DataGrid.CellRenderers.Add("StackedHeader", new StackedHeaderRenderer());
  585. }
  586. }
  587. private readonly List<DynamicColumnBase> ColumnList = new();
  588. private List<DynamicActionColumn> ActionColumns = new();
  589. private DynamicColumnBase? GetColumn(int index) =>
  590. index >= 0 && index < ColumnList.Count ? ColumnList[index] : null;
  591. int IDynamicGridUIComponent<T>.DesiredWidth()
  592. {
  593. return this.DesiredWidth();
  594. }
  595. private void ResizeColumns(SfDataGrid grid, double width, double height)
  596. {
  597. if (Parent.Data == null || width <= 0)
  598. return;
  599. grid.Dispatcher.BeginInvoke(() =>
  600. {
  601. foreach (var (index, size) in this.CalculateColumnSizes(width))
  602. DataGrid.Columns[index].Width = Math.Max(0.0F, size);
  603. });
  604. }
  605. private ObservableCollection<ISummaryColumn> Summaries = new();
  606. private void LoadActionColumns(DynamicActionColumnPosition position)
  607. {
  608. for (var i = 0; i < ActionColumns.Count; i++)
  609. {
  610. var column = ActionColumns[i];
  611. if (column.Position == position)
  612. {
  613. //String sColName = String.Format("ActionColumn{0}{1}", i, position == DynamicActionColumnPosition.Start ? "L" : "R");
  614. var sColName = string.Format("ActionColumn{0}", i);
  615. gridRowResizingOptions.ExcludeColumns.Add(sColName);
  616. var summary = column.Summary();
  617. if (summary != null)
  618. {
  619. summary.Name = sColName;
  620. summary.MappingName = sColName;
  621. Summaries.Add(summary);
  622. }
  623. if (column is DynamicImageColumn imgcol)
  624. {
  625. var newcol = new GridImageColumn();
  626. newcol.MappingName = sColName;
  627. //newcol.Stretch = Stretch.Uniform;
  628. newcol.Width = column.Width == 0 ? DataGrid.RowHeight : column.Width;
  629. newcol.Padding = new Thickness(4);
  630. newcol.ImageHeight = DataGrid.RowHeight - 8;
  631. newcol.ImageWidth = DataGrid.RowHeight - 8;
  632. newcol.ColumnSizer = GridLengthUnitType.None;
  633. newcol.HeaderText = column.HeaderText;
  634. newcol.AllowSorting = false;
  635. ApplyFilterStyle(newcol, true, true);
  636. newcol.ShowToolTip = column.ToolTip != null;
  637. newcol.ShowHeaderToolTip = column.ToolTip != null;
  638. var style = new Style();
  639. style.Setters.Add(new Setter(Control.BackgroundProperty, new SolidColorBrush(Colors.Gainsboro)));
  640. style.Setters.Add(new Setter(Control.IsEnabledProperty, false));
  641. newcol.FilterRowCellStyle = style;
  642. var headstyle = new Style(typeof(GridHeaderCellControl));
  643. headstyle.Setters.Add(new Setter(Control.BackgroundProperty, new SolidColorBrush(Colors.Gainsboro)));
  644. headstyle.Setters.Add(new Setter(Control.ForegroundProperty, new SolidColorBrush(Colors.Black)));
  645. headstyle.Setters.Add(new Setter(Control.FontSizeProperty, 12D));
  646. if (!string.IsNullOrWhiteSpace(column.HeaderText))
  647. {
  648. //headstyle.Setters.Add(new Setter(LayoutTransformProperty, new RotateTransform(270.0F)));
  649. headstyle.Setters.Add(new Setter(Control.BorderThicknessProperty, new Thickness(0.0, 0.0, 0, 0)));
  650. headstyle.Setters.Add(new Setter(Control.MarginProperty, new Thickness(0, 0, 1, 1)));
  651. if (imgcol.VerticalHeader)
  652. headstyle.Setters.Add(new Setter(Control.TemplateProperty,
  653. Application.Current.Resources["VerticalColumnHeader"] as ControlTemplate));
  654. }
  655. else
  656. {
  657. var image = imgcol.Image?.Invoke(null);
  658. if (image != null)
  659. {
  660. var template = new ControlTemplate(typeof(GridHeaderCellControl));
  661. var border = new FrameworkElementFactory(typeof(Border));
  662. border.SetValue(Border.BackgroundProperty, new SolidColorBrush(Colors.Gainsboro));
  663. border.SetValue(Border.PaddingProperty, new Thickness(4));
  664. border.SetValue(Control.MarginProperty, new Thickness(0, 0, 1, 1));
  665. var img = new FrameworkElementFactory(typeof(Image));
  666. img.SetValue(Image.SourceProperty, image);
  667. border.AppendChild(img);
  668. template.VisualTree = border;
  669. headstyle.Setters.Add(new Setter(Control.TemplateProperty, template));
  670. }
  671. }
  672. newcol.HeaderStyle = headstyle;
  673. DataGrid.Columns.Add(newcol);
  674. ColumnList.Add(column);
  675. }
  676. else if (column is DynamicTextColumn txtCol)
  677. {
  678. var newcol = new GridTextColumn();
  679. gridRowResizingOptions.ExcludeColumns.Add(sColName);
  680. newcol.TextWrapping = TextWrapping.NoWrap;
  681. newcol.TextAlignment = txtCol.Alignment == Alignment.NotSet
  682. ? TextAlignment.Left
  683. : txtCol.Alignment == Alignment.BottomLeft || txtCol.Alignment == Alignment.MiddleLeft ||
  684. txtCol.Alignment == Alignment.TopLeft
  685. ? TextAlignment.Left
  686. : txtCol.Alignment == Alignment.BottomCenter || txtCol.Alignment == Alignment.MiddleCenter ||
  687. txtCol.Alignment == Alignment.TopCenter
  688. ? TextAlignment.Center
  689. : TextAlignment.Right;
  690. newcol.AllowEditing = false;
  691. newcol.UpdateTrigger = UpdateSourceTrigger.PropertyChanged;
  692. newcol.MappingName = sColName;
  693. newcol.Width = column.Width;
  694. newcol.ColumnSizer = GridLengthUnitType.None;
  695. newcol.HeaderText = column.HeaderText;
  696. newcol.AllowFiltering = column.Filters != null && column.Filters.Any();
  697. newcol.AllowSorting = false;
  698. newcol.FilterRowOptionsVisibility = Visibility.Collapsed;
  699. newcol.ShowHeaderToolTip = column.ToolTip != null;
  700. var style = new Style();
  701. style.Setters.Add(new Setter(Control.BackgroundProperty, new SolidColorBrush(Colors.Gainsboro)));
  702. style.Setters.Add(new Setter(Control.IsEnabledProperty, false));
  703. newcol.FilterRowCellStyle = style;
  704. var headstyle = new Style(typeof(GridHeaderCellControl));
  705. headstyle.Setters.Add(new Setter(Control.BackgroundProperty, new SolidColorBrush(Colors.Gainsboro)));
  706. headstyle.Setters.Add(new Setter(Control.ForegroundProperty, new SolidColorBrush(Colors.Black)));
  707. headstyle.Setters.Add(new Setter(Control.FontSizeProperty, 12D));
  708. headstyle.Setters.Add(new Setter(Control.BorderThicknessProperty, new Thickness(0.0, 0.0, 0, 0)));
  709. headstyle.Setters.Add(new Setter(Control.MarginProperty, new Thickness(0, 0, 1, 1)));
  710. if (txtCol.VerticalHeader)
  711. {
  712. headstyle.Setters.Add(new Setter(Control.HorizontalContentAlignmentProperty, HorizontalAlignment.Left));
  713. headstyle.Setters.Add(new Setter(Control.TemplateProperty,
  714. Application.Current.Resources["VerticalColumnHeader"] as ControlTemplate));
  715. }
  716. newcol.HeaderStyle = headstyle;
  717. var cellstyle = new Style();
  718. cellstyle.Setters.Add(new Setter(Control.BackgroundProperty,
  719. new Binding()
  720. {
  721. Path = new PropertyPath("."), Converter = CellBackgroundConverter,
  722. ConverterParameter = column
  723. }));
  724. cellstyle.Setters.Add(new Setter(Control.ForegroundProperty,
  725. new Binding()
  726. { Converter = CellForegroundConverter, ConverterParameter = column }));
  727. cellstyle.Setters.Add(new Setter(Control.FontSizeProperty,
  728. new Binding()
  729. { Converter = CellFontSizeConverter, ConverterParameter = column }));
  730. cellstyle.Setters.Add(new Setter(Control.FontStyleProperty,
  731. new Binding()
  732. { Converter = CellFontStyleConverter, ConverterParameter = column }));
  733. cellstyle.Setters.Add(new Setter(Control.FontWeightProperty,
  734. new Binding()
  735. { Converter = CellFontWeightConverter, ConverterParameter = column }));
  736. newcol.CellStyle = cellstyle;
  737. DataGrid.Columns.Add(newcol);
  738. ColumnList.Add(column);
  739. }
  740. else if (column is DynamicTemplateColumn tmplCol)
  741. {
  742. var newcol = new GridTemplateColumn();
  743. newcol.CellTemplateSelector = new TemplateColumnSelector(this, tmplCol.Template);
  744. newcol.AllowEditing = false;
  745. newcol.UpdateTrigger = UpdateSourceTrigger.PropertyChanged;
  746. newcol.MappingName = sColName;
  747. newcol.Width = tmplCol.Width;
  748. newcol.ColumnSizer = GridLengthUnitType.None;
  749. newcol.HeaderText = column.HeaderText;
  750. newcol.AllowFiltering = false;
  751. newcol.AllowSorting = false;
  752. newcol.FilterRowOptionsVisibility = Visibility.Collapsed;
  753. newcol.ShowToolTip = false;
  754. newcol.ShowHeaderToolTip = false;
  755. var style = new Style();
  756. style.Setters.Add(new Setter(Control.BackgroundProperty, new SolidColorBrush(Colors.Gainsboro)));
  757. style.Setters.Add(new Setter(Control.IsEnabledProperty, false));
  758. newcol.FilterRowCellStyle = style;
  759. var headstyle = new Style(typeof(GridHeaderCellControl));
  760. headstyle.Setters.Add(new Setter(Control.BackgroundProperty, new SolidColorBrush(Colors.Gainsboro)));
  761. headstyle.Setters.Add(new Setter(Control.ForegroundProperty, new SolidColorBrush(Colors.Black)));
  762. headstyle.Setters.Add(new Setter(Control.FontSizeProperty, 12D));
  763. headstyle.Setters.Add(new Setter(Control.MarginProperty, new Thickness(0, 0, 1, 1)));
  764. headstyle.Setters.Add(new Setter(Control.BorderThicknessProperty, new Thickness(0.0)));
  765. newcol.HeaderStyle = headstyle;
  766. var cellstyle = new Style();
  767. cellstyle.Setters.Add(new Setter(Control.BackgroundProperty,
  768. new Binding()
  769. {
  770. Path = new PropertyPath("."), Converter = CellBackgroundConverter,
  771. ConverterParameter = column
  772. }));
  773. cellstyle.Setters.Add(new Setter(Control.ForegroundProperty,
  774. new Binding()
  775. { Converter = CellForegroundConverter, ConverterParameter = column }));
  776. cellstyle.Setters.Add(new Setter(Control.FontSizeProperty,
  777. new Binding()
  778. { Converter = CellFontSizeConverter, ConverterParameter = column }));
  779. cellstyle.Setters.Add(new Setter(Control.FontStyleProperty,
  780. new Binding()
  781. { Converter = CellFontStyleConverter, ConverterParameter = column }));
  782. cellstyle.Setters.Add(new Setter(Control.FontWeightProperty,
  783. new Binding()
  784. { Converter = CellFontWeightConverter, ConverterParameter = column }));
  785. newcol.CellStyle = cellstyle;
  786. DataGrid.Columns.Add(newcol);
  787. ColumnList.Add(column);
  788. }
  789. }
  790. }
  791. }
  792. public class TemplateColumnSelector(DynamicGridGridUIComponent<T> parent, Func<CoreRow, FrameworkElement?> dataTemplate) : DataTemplateSelector
  793. {
  794. public Func<CoreRow, FrameworkElement?> DataTemplate { get; init; } = dataTemplate;
  795. public DynamicGridGridUIComponent<T> Parent { get; init; } = parent;
  796. public override DataTemplate? SelectTemplate(object item, DependencyObject container)
  797. {
  798. if (item is not DataRowView) return null;
  799. CoreRow? row;
  800. if(item is DataRowView view && Parent.DataGridItems is DataTable table)
  801. {
  802. var rowIdx = table.Rows.IndexOf(view.Row);
  803. if (rowIdx < 0)
  804. {
  805. row = null;
  806. }
  807. else
  808. {
  809. row = Parent.Parent.Data.Rows[rowIdx];
  810. }
  811. }
  812. else
  813. {
  814. row = null;
  815. }
  816. if (row is null) return null;
  817. return TemplateGenerator.CreateDataTemplate(() =>
  818. {
  819. return DataTemplate(row);
  820. });
  821. }
  822. }
  823. private void ApplyFilterStyle(GridColumn column, bool filtering, bool isactioncolumn)
  824. {
  825. var filterstyle = new Style();
  826. if (filtering)
  827. {
  828. filterstyle.Setters.Add(new Setter(Control.BackgroundProperty, DynamicGridUtils.FilterBackground));
  829. column.ImmediateUpdateColumnFilter = true;
  830. column.ColumnFilter = ColumnFilter.Value;
  831. column.FilterRowCondition = FilterRowCondition.Contains;
  832. column.FilterRowOptionsVisibility = Visibility.Collapsed;
  833. column.AllowBlankFilters = true;
  834. column.AllowSorting = isactioncolumn
  835. ? false
  836. : Parent.CanSort();
  837. }
  838. else
  839. {
  840. filterstyle.Setters.Add(new Setter(Control.BackgroundProperty, new SolidColorBrush(Colors.Gainsboro)));
  841. filterstyle.Setters.Add(new Setter(Control.IsEnabledProperty, false));
  842. column.ColumnFilter = ColumnFilter.Value;
  843. column.AllowFiltering = false;
  844. column.AllowSorting = false;
  845. column.FilterRowEditorType = "TextBox";
  846. column.FilterRowOptionsVisibility = Visibility.Collapsed;
  847. }
  848. column.FilterRowCellStyle = filterstyle;
  849. }
  850. private void LoadDataColumns(DynamicGridColumns columns)
  851. {
  852. foreach (var column in columns)
  853. {
  854. if (this.CreateEditorColumn(column, out var newcol, out var prop))
  855. {
  856. newcol.GetEntity = () => _editingObject.Object;
  857. newcol.EntityChanged += DoEntityChanged;
  858. if (!newcol.VariableHeight)
  859. gridRowResizingOptions.ExcludeColumns.Add(newcol.MappingName);
  860. var newColumn = newcol.CreateGridColumn();
  861. newColumn.AllowEditing = newcol.Editable && Parent.IsDirectEditMode();
  862. var summary = newcol.Summary();
  863. if (summary != null)
  864. Summaries.Add(summary);
  865. ApplyFilterStyle(newColumn, newcol.Filtered, false);
  866. var headstyle = new Style(typeof(GridHeaderCellControl));
  867. headstyle.Setters.Add(new Setter(Control.BackgroundProperty, new SolidColorBrush(Colors.Gainsboro)));
  868. headstyle.Setters.Add(new Setter(Control.ForegroundProperty, new SolidColorBrush(Colors.Black)));
  869. headstyle.Setters.Add(new Setter(Control.FontSizeProperty, 12D));
  870. newColumn.HeaderStyle = headstyle;
  871. var cellstyle = new Style();
  872. if (Parent.IsDirectEditMode())
  873. {
  874. if (prop.Editor is null || !prop.Editor.Editable.IsDirectEditable())
  875. {
  876. cellstyle.Setters.Add(new Setter(Control.BackgroundProperty,
  877. new SolidColorBrush(Colors.WhiteSmoke)));
  878. newColumn.AllowEditing = false;
  879. }
  880. else
  881. {
  882. cellstyle.Setters.Add(new Setter(Control.BackgroundProperty,
  883. new SolidColorBrush(Colors.LightYellow)));
  884. newColumn.AllowEditing = true;
  885. }
  886. cellstyle.Setters.Add(new Setter(Control.ForegroundProperty, new SolidColorBrush(Colors.Black)));
  887. newColumn.CellStyle = cellstyle;
  888. }
  889. else
  890. {
  891. cellstyle.Setters.Add(new Setter(Control.BackgroundProperty,
  892. new Binding()
  893. {
  894. Path = new PropertyPath("."), Converter = CellBackgroundConverter,
  895. ConverterParameter = column
  896. }));
  897. cellstyle.Setters.Add(new Setter(Control.ForegroundProperty,
  898. new Binding()
  899. { Converter = CellForegroundConverter, ConverterParameter = column }));
  900. cellstyle.Setters.Add(new Setter(Control.FontSizeProperty,
  901. new Binding()
  902. { Converter = CellFontSizeConverter, ConverterParameter = column }));
  903. cellstyle.Setters.Add(new Setter(Control.FontStyleProperty,
  904. new Binding()
  905. { Converter = CellFontStyleConverter, ConverterParameter = column }));
  906. cellstyle.Setters.Add(new Setter(Control.FontWeightProperty,
  907. new Binding()
  908. { Converter = CellFontWeightConverter, ConverterParameter = column }));
  909. newColumn.CellStyle = cellstyle;
  910. }
  911. DataGrid.Columns.Add(newColumn);
  912. ColumnList.Add(column);
  913. foreach (var extra in newcol.ExtraColumns)
  914. Parent.AddHiddenColumn(extra);
  915. }
  916. }
  917. }
  918. private void LoadSummaries()
  919. {
  920. if (Summaries.Any())
  921. {
  922. DataGrid.CellRenderers.Remove("TableSummary");
  923. DataGrid.CellRenderers.Add("TableSummary", new DynamicGridAggregateRenderer());
  924. DataGrid.TableSummaryRows.Add(new GridTableSummaryRow
  925. {
  926. ShowSummaryInRow = false,
  927. Position = TableSummaryRowPosition.Bottom,
  928. SummaryColumns = Summaries
  929. });
  930. }
  931. }
  932. public void RefreshColumns(DynamicGridColumns columns, DynamicActionColumns actionColumns, DynamicGridColumnGroupings groupings)
  933. {
  934. // Yo, please don't remove this.
  935. // 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
  936. // 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(),
  937. // and thus some mega problems (perhaps even exceptions within Syncfusion) were occurring, and this seems to fix it.
  938. // I don't pretend to know why it works; this is probably the strangest problem I've ever come across.
  939. DataGrid.ItemsSource = null;
  940. DataGrid.Columns.Suspend();
  941. ColumnList.Clear();
  942. DataGrid.Columns.Clear();
  943. DataGrid.TableSummaryRows.Clear();
  944. gridRowResizingOptions.ExcludeColumns = new List<string>();
  945. ActionColumns = actionColumns.ToList();
  946. Summaries.Clear();
  947. LoadActionColumns(DynamicActionColumnPosition.Start);
  948. LoadDataColumns(columns);
  949. LoadActionColumns(DynamicActionColumnPosition.End);
  950. LoadSummaries();
  951. LoadStackedHeaders(groupings);
  952. DataGrid.Columns.Resume();
  953. DataGrid.RefreshColumns();
  954. foreach (var key in _filterpredicates.Keys.ToArray())
  955. if (DataGrid.Columns.Any(x => string.Equals(x.MappingName, key)))
  956. {
  957. var predicates = Serialization.Deserialize<List<FilterPredicate>>(_filterpredicates[key]);
  958. foreach (var predicate in predicates)
  959. {
  960. DataGrid.Columns[key].FilterPredicates.Add(predicate);
  961. DataGrid.Columns[key].FilteredFrom = FilteredFrom.FilterRow;
  962. }
  963. }
  964. else
  965. {
  966. _filterpredicates.Remove(key);
  967. }
  968. ResizeColumns(DataGrid, DataGrid.ActualWidth - 2, DataGrid.ActualHeight - 2);
  969. }
  970. #endregion
  971. #region Data
  972. private bool _invalidating = false;
  973. public void BeforeRefresh()
  974. {
  975. DataGrid.SelectionForegroundBrush = GetCellSelectionForegroundBrush();
  976. DataGrid.RowSelectionBrush = GetCellSelectionBackgroundBrush();
  977. }
  978. public void RefreshData(CoreTable data)
  979. {
  980. var defaults = new List<object?>();
  981. var result = new DataTable();
  982. foreach (var column in data.Columns)
  983. {
  984. var colname = column.ColumnName.Replace('.', '_');
  985. if (!result.Columns.Contains(colname))
  986. {
  987. result.Columns.Add(colname, column.DataType);
  988. if (!Parent.IsDirectEditMode())
  989. defaults.Add(column.DataType.GetDefault());
  990. }
  991. }
  992. for (var i = 0; i < ActionColumns.Count; i++)
  993. result.Columns.Add(string.Format("ActionColumn{0}", i),
  994. ActionColumns[i] is DynamicImageColumn
  995. ? typeof(BitmapImage)
  996. : typeof(String)
  997. );
  998. foreach (var row in data.Rows)
  999. {
  1000. var newrow = result.NewRow();
  1001. CoreRowToDataRow(newrow, row, defaults);
  1002. result.Rows.Add(newrow);
  1003. }
  1004. result.ColumnChanged += Result_ColumnChanged;
  1005. //int rowIndex = DataGrid.SelectionController.CurrentCellManager.CurrentRowColumnIndex.RowIndex;
  1006. //int columnIndex = DataGrid.SelectionController.CurrentCellManager.CurrentRowColumnIndex.ColumnIndex;
  1007. //int scrollRowIndex = DataGrid.GetVisualContainer().ScrollRows.LastBodyVisibleLineIndex;
  1008. DataGrid.ItemsSource = result;
  1009. //this.DataGrid.ScrollInView(new Syncfusion.UI.Xaml.ScrollAxis.RowColumnIndex(scrollRowIndex, columnIndex));
  1010. ResizeColumns(DataGrid, DataGrid.ActualWidth - 1, DataGrid.ActualHeight);
  1011. UpdateRecordCount();
  1012. }
  1013. public void InvalidateRow(CoreRow row)
  1014. {
  1015. var table = DataGridItems;
  1016. if(table is null)
  1017. {
  1018. return;
  1019. }
  1020. _invalidating = true;
  1021. var rowdata = new List<object?>(row.Values);
  1022. foreach (var ac in ActionColumns)
  1023. rowdata.Add(ac.Data(row));
  1024. var datarow = DataGridItems.Rows[row.Index];
  1025. for (var i = 0; i < rowdata.Count; i++)
  1026. datarow[i] = rowdata[i] ?? DBNull.Value;
  1027. _invalidating = false;
  1028. //datarow.ItemArray = rowdata.ToArray();
  1029. }
  1030. private void CoreRowToDataRow(DataRow newrow, CoreRow row, List<object?> defaults)
  1031. {
  1032. var rowdata = new List<object?>(row.Values);
  1033. foreach (var ac in ActionColumns)
  1034. rowdata.Add(ac.Data(row));
  1035. try
  1036. {
  1037. var data = ProcessRow(rowdata, defaults).ToArray();
  1038. newrow.ItemArray = data;
  1039. }
  1040. catch (Exception)
  1041. {
  1042. throw;
  1043. }
  1044. }
  1045. private static IEnumerable<object?> ProcessRow(List<object?> values, List<object?> defaults)
  1046. {
  1047. if (defaults == null || !defaults.Any())
  1048. return values;
  1049. var result = new List<object?>();
  1050. for (var i = 0; i < values.Count; i++)
  1051. {
  1052. var value = values[i];
  1053. var defaultvalue = i < defaults.Count ? defaults[i] : null;
  1054. result.Add(value == null || (value.Equals(defaultvalue) && !value.GetType().IsEnum) ? null : value);
  1055. }
  1056. return result;
  1057. }
  1058. #endregion
  1059. #region Direct Edit
  1060. private bool bChanged;
  1061. private class DirectEditingObject
  1062. {
  1063. public T Object { get; set; }
  1064. public CoreRow Row { get; set; }
  1065. public DataRow? DataRow { get; set; }
  1066. public DirectEditingObject(T obj, CoreRow row, DataRow? dataRow)
  1067. {
  1068. Object = obj;
  1069. Row = row;
  1070. DataRow = dataRow;
  1071. }
  1072. }
  1073. private DirectEditingObject? _editingObject;
  1074. private DirectEditingObject EnsureEditingObject(CoreRow row)
  1075. {
  1076. _editingObject ??= new(Parent.LoadItem(row), row, DataGridItems?.Rows[row.Index]);
  1077. return _editingObject;
  1078. }
  1079. private DataRow? GetDataRow(CoreRow row)
  1080. {
  1081. return DataGridItems?.Rows[row.Index];
  1082. }
  1083. void IDynamicGridUIComponent<T>.UpdateCell(CoreRow row, string column, object? value)
  1084. {
  1085. var dataRow = GetDataRow(row);
  1086. var datacolname = column.Replace(".", "_");
  1087. if(dataRow is not null)
  1088. {
  1089. dataRow[datacolname] = value ?? DBNull.Value;
  1090. }
  1091. }
  1092. void IDynamicGridUIComponent<T>.UpdateRow(CoreRow row)
  1093. {
  1094. var dataRow = GetDataRow(row);
  1095. if(dataRow is not null)
  1096. {
  1097. foreach(var (key, value) in row)
  1098. {
  1099. var datacolname = key.Replace(".", "_");
  1100. var dataValue = dataRow[datacolname];
  1101. if (!Equals(dataValue, value) && !(value is null && dataValue == DBNull.Value))
  1102. {
  1103. dataRow[datacolname] = value ?? DBNull.Value;
  1104. }
  1105. }
  1106. for (var i = 0; i < ActionColumns.Count; i++)
  1107. dataRow[$"ActionColumn{i}"] = ActionColumns[i].Data(row);
  1108. }
  1109. }
  1110. private void DoEntityChanged(IDynamicColumnBase column, DynamicColumnEntityChangedEventArgs args)
  1111. {
  1112. if (_editingObject is null) return;
  1113. Parent.EntityChanged(_editingObject.Object, _editingObject.Row, args.ColumnName, args.Changes);
  1114. }
  1115. private void UpdateData(string column, Dictionary<CoreColumn, object?> updates)
  1116. {
  1117. if (_editingObject is null)
  1118. return;
  1119. var coreRow = _editingObject.Row;
  1120. Parent.UpdateData(_editingObject.Object, coreRow, column, updates);
  1121. }
  1122. private void UpdateData(int rowIndex, int columnIndex)
  1123. {
  1124. var table = DataGridItems;
  1125. if (table is null)
  1126. return;
  1127. if (GetColumn(columnIndex) is DynamicGridColumn gridcol)
  1128. {
  1129. var datacol = Parent.Data.Columns.FirstOrDefault(x => x.ColumnName.Equals(gridcol.ColumnName));
  1130. if (datacol != null)
  1131. {
  1132. var datacolindex = Parent.Data.Columns.IndexOf(datacol);
  1133. var value = table.Rows[rowIndex][datacolindex];
  1134. if (value is DBNull)
  1135. value = CoreUtils.GetDefault(datacol.DataType);
  1136. UpdateData(datacol.ColumnName, new Dictionary<CoreColumn, object?>() { { datacol, value } });
  1137. }
  1138. }
  1139. }
  1140. private void DataGrid_CurrentCellBeginEdit(object? sender, CurrentCellBeginEditEventArgs e)
  1141. {
  1142. var table = DataGridItems;
  1143. var row = GetRowFromIndex(e.RowColumnIndex.RowIndex);
  1144. if (table is null || row is null)
  1145. return;
  1146. EnsureEditingObject(row);
  1147. var column = DataGrid.Columns[e.RowColumnIndex.ColumnIndex] as GridComboBoxColumn;
  1148. if (column != null && column.ItemsSource == null)
  1149. {
  1150. var colname = column.MappingName;
  1151. var colno = table.Columns.IndexOf(colname);
  1152. var property = Parent.Data.Columns[colno].ColumnName;
  1153. var prop = CoreUtils.GetProperty(typeof(T), property);
  1154. var editor = prop.GetEditor();
  1155. if (editor is ILookupEditor lookupEditor)
  1156. {
  1157. if (!Lookups.ContainsKey(property))
  1158. Lookups[property] = lookupEditor.Values(typeof(T), property);
  1159. var combo = column;
  1160. combo.ItemsSource = Lookups[property].ToDictionary(Lookups[property].Columns[0].ColumnName, "Display");
  1161. combo.SelectedValuePath = "Key";
  1162. combo.DisplayMemberPath = "Value";
  1163. }
  1164. }
  1165. bChanged = false;
  1166. }
  1167. private void Result_ColumnChanged(object sender, DataColumnChangeEventArgs e)
  1168. {
  1169. if (_invalidating) return;
  1170. if (sender is not DataTable table) return;
  1171. var rowIdx = table.Rows.IndexOf(e.Row);
  1172. if (rowIdx < 0)
  1173. return;
  1174. var row = Parent.Data.Rows[rowIdx];
  1175. var colIdx = table.Columns.IndexOf(e.Column);
  1176. if (colIdx < 0 || colIdx >= Parent.Data.Columns.Count)
  1177. return;
  1178. var data = Parent.Data;
  1179. var dataCol = Parent.Data.Columns[colIdx];
  1180. var col = ColumnList.OfType<DynamicGridColumn>()
  1181. .FirstOrDefault(x => x.ColumnName.Equals(dataCol.ColumnName));
  1182. if (col is null)
  1183. return;
  1184. if (col is DynamicGridCheckBoxColumn<T>)
  1185. {
  1186. EnsureEditingObject(row);
  1187. if(_editingObject is not null)
  1188. {
  1189. var value = e.Row[e.Column!];
  1190. if (value is DBNull)
  1191. value = CoreUtils.GetDefault(dataCol.DataType);
  1192. _invalidating = true;
  1193. UpdateData(dataCol.ColumnName, new Dictionary<CoreColumn, object?>() { { dataCol, value } });
  1194. _invalidating = false;
  1195. }
  1196. _editingObject = null;
  1197. }
  1198. if (_editingObject is not null)
  1199. bChanged = true;
  1200. }
  1201. private void DataGrid_CurrentCellDropDownSelectionChanged(object? sender,
  1202. CurrentCellDropDownSelectionChangedEventArgs e)
  1203. {
  1204. var row = GetRowFromIndex(e.RowColumnIndex.RowIndex);
  1205. if (row is null)
  1206. return;
  1207. EnsureEditingObject(row);
  1208. if ((_editingObject is not null) && (e.SelectedItem is Tuple<object?, string> tuple))
  1209. {
  1210. var mappedname = DataGrid.Columns[e.RowColumnIndex.ColumnIndex].MappingName;
  1211. var colno = DataGridItems.Columns.IndexOf(mappedname);
  1212. var corecol = Parent.Data.Columns[colno].ColumnName;
  1213. var updates = new Dictionary<CoreColumn, object?>();
  1214. var prefix = String.Join(".", corecol.Split(".").Reverse().Skip(1).Reverse());
  1215. var field = corecol.Split(".").Last();
  1216. var prop = CoreUtils.GetProperty(typeof(T), corecol);
  1217. if (prop.GetEditor() is ILookupEditor editor)
  1218. {
  1219. var data = editor.Values(typeof(T), corecol);
  1220. var lookuprow = data.Rows.FirstOrDefault(r => Equals(r[field], tuple.Item1))
  1221. ?? data.NewRow(true);
  1222. foreach (CoreColumn lookupcol in data.Columns)
  1223. {
  1224. var columnname = String.IsNullOrWhiteSpace(prefix)
  1225. ? lookupcol.ColumnName
  1226. : String.Join(".", prefix, lookupcol.ColumnName);
  1227. var updatecol = Parent.Data.Columns.FirstOrDefault(x => String.Equals(x.ColumnName, columnname));
  1228. if (updatecol != null)
  1229. updates[updatecol] = lookuprow[lookupcol.ColumnName];
  1230. }
  1231. UpdateData(corecol, updates);
  1232. bChanged = true;
  1233. }
  1234. }
  1235. }
  1236. private void DataGrid_CurrentCellEndEdit(object? sender, CurrentCellEndEditEventArgs e)
  1237. {
  1238. if (_editingObject is not null && bChanged)
  1239. {
  1240. UpdateData(_editingObject.Row.Index, e.RowColumnIndex.ColumnIndex);
  1241. }
  1242. if (bChanged)
  1243. Parent.DoChanged();
  1244. bChanged = false;
  1245. _editingObject = null;
  1246. // 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
  1247. // editing the filter row. It seems that this causes Syncfusion to commit the filter predicates internally, which means that after leaving a
  1248. // filter row cell, the filter remained even once it was cleared, meaning a refresh was necessary to get the data back.
  1249. // I've tested on Bills to see if editing works with this empty, and it seems so.
  1250. //DataGridItems?.AcceptChanges();
  1251. }
  1252. private void DataGrid_PreviewKeyUp(object sender, KeyEventArgs e)
  1253. {
  1254. if (e.Key == Key.OemPeriod)
  1255. {
  1256. var editor = e.OriginalSource as TimeSpanEdit;
  1257. if (editor != null && editor.SelectionStart < 2) editor.SelectionStart = 3;
  1258. }
  1259. else if (e.Key == Key.Tab)
  1260. {
  1261. if (Parent.IsDirectEditMode())
  1262. {
  1263. DataGrid.SelectionController.CurrentCellManager.EndEdit();
  1264. DataGrid.MoveFocus(new TraversalRequest(FocusNavigationDirection.Right));
  1265. DataGrid.SelectionController.CurrentCellManager.BeginEdit();
  1266. e.Handled = true;
  1267. }
  1268. }
  1269. }
  1270. #endregion
  1271. #region Drag + Drop
  1272. private void DataGrid_DragOver(object sender, DragEventArgs e)
  1273. {
  1274. Parent.DragOver(sender, e);
  1275. }
  1276. private void DataGrid_Drop(object sender, DragEventArgs e)
  1277. {
  1278. Parent.Drop(sender, e);
  1279. }
  1280. private void RowDragDropController_DragStart(object? sender, GridRowDragStartEventArgs e)
  1281. {
  1282. var rows = e.DraggingRecords.Select(record =>
  1283. {
  1284. var rowIndex = DataGrid.ResolveToRowIndex(record);
  1285. return GetRowFromIndex(rowIndex);
  1286. }).NotNull().ToArray();
  1287. Parent.DragStart(sender, rows);
  1288. }
  1289. #endregion
  1290. }