DynamicGridGridUIComponent.cs 62 KB

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