DynamicGridGridUIComponent.cs 62 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571
  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 = new DynamicGridCellStyleParameters(column,DependencyProperty.UnsetValue)
  723. }));
  724. cellstyle.Setters.Add(new Setter(Control.ForegroundProperty,
  725. new Binding()
  726. {
  727. Converter = CellForegroundConverter,
  728. ConverterParameter = new DynamicGridCellStyleParameters(column,DependencyProperty.UnsetValue)
  729. }));
  730. cellstyle.Setters.Add(new Setter(Control.FontSizeProperty,
  731. new Binding()
  732. {
  733. Converter = CellFontSizeConverter,
  734. ConverterParameter = new DynamicGridCellStyleParameters(column,DependencyProperty.UnsetValue)
  735. }));
  736. cellstyle.Setters.Add(new Setter(Control.FontStyleProperty,
  737. new Binding()
  738. {
  739. Converter = CellFontStyleConverter,
  740. ConverterParameter = new DynamicGridCellStyleParameters(column,DependencyProperty.UnsetValue)
  741. }));
  742. cellstyle.Setters.Add(new Setter(Control.FontWeightProperty,
  743. new Binding()
  744. {
  745. Converter = CellFontWeightConverter,
  746. ConverterParameter = new DynamicGridCellStyleParameters(column,DependencyProperty.UnsetValue)
  747. }));
  748. newcol.CellStyle = cellstyle;
  749. DataGrid.Columns.Add(newcol);
  750. ColumnList.Add(column);
  751. }
  752. else if (column is DynamicTemplateColumn tmplCol)
  753. {
  754. var newcol = new GridTemplateColumn();
  755. newcol.CellTemplateSelector = new TemplateColumnSelector(this, tmplCol.Template);
  756. newcol.AllowEditing = false;
  757. newcol.UpdateTrigger = UpdateSourceTrigger.PropertyChanged;
  758. newcol.MappingName = sColName;
  759. newcol.Width = tmplCol.Width;
  760. newcol.ColumnSizer = GridLengthUnitType.None;
  761. newcol.HeaderText = column.HeaderText;
  762. newcol.AllowFiltering = false;
  763. newcol.AllowSorting = false;
  764. newcol.FilterRowOptionsVisibility = Visibility.Collapsed;
  765. newcol.ShowToolTip = false;
  766. newcol.ShowHeaderToolTip = false;
  767. var style = new Style();
  768. style.Setters.Add(new Setter(Control.BackgroundProperty, new SolidColorBrush(Colors.Gainsboro)));
  769. style.Setters.Add(new Setter(Control.IsEnabledProperty, false));
  770. newcol.FilterRowCellStyle = style;
  771. var headstyle = new Style(typeof(GridHeaderCellControl));
  772. headstyle.Setters.Add(new Setter(Control.BackgroundProperty, new SolidColorBrush(Colors.Gainsboro)));
  773. headstyle.Setters.Add(new Setter(Control.ForegroundProperty, new SolidColorBrush(Colors.Black)));
  774. headstyle.Setters.Add(new Setter(Control.FontSizeProperty, 12D));
  775. headstyle.Setters.Add(new Setter(Control.MarginProperty, new Thickness(0, 0, 1, 1)));
  776. headstyle.Setters.Add(new Setter(Control.BorderThicknessProperty, new Thickness(0.0)));
  777. newcol.HeaderStyle = headstyle;
  778. var cellstyle = new Style();
  779. cellstyle.Setters.Add(new Setter(Control.BackgroundProperty,
  780. new Binding()
  781. {
  782. Path = new PropertyPath("."), Converter = CellBackgroundConverter,
  783. ConverterParameter = column
  784. }));
  785. cellstyle.Setters.Add(new Setter(Control.ForegroundProperty,
  786. new Binding()
  787. { Converter = CellForegroundConverter, ConverterParameter = column }));
  788. cellstyle.Setters.Add(new Setter(Control.FontSizeProperty,
  789. new Binding()
  790. { Converter = CellFontSizeConverter, ConverterParameter = column }));
  791. cellstyle.Setters.Add(new Setter(Control.FontStyleProperty,
  792. new Binding()
  793. { Converter = CellFontStyleConverter, ConverterParameter = column }));
  794. cellstyle.Setters.Add(new Setter(Control.FontWeightProperty,
  795. new Binding()
  796. { Converter = CellFontWeightConverter, ConverterParameter = column }));
  797. newcol.CellStyle = cellstyle;
  798. DataGrid.Columns.Add(newcol);
  799. ColumnList.Add(column);
  800. }
  801. }
  802. }
  803. }
  804. public class TemplateColumnSelector(DynamicGridGridUIComponent<T> parent, Func<CoreRow, FrameworkElement?> dataTemplate) : DataTemplateSelector
  805. {
  806. public Func<CoreRow, FrameworkElement?> DataTemplate { get; init; } = dataTemplate;
  807. public DynamicGridGridUIComponent<T> Parent { get; init; } = parent;
  808. public override DataTemplate? SelectTemplate(object item, DependencyObject container)
  809. {
  810. if (item is not DataRowView) return null;
  811. CoreRow? row;
  812. if(item is DataRowView view && Parent.DataGridItems is DataTable table)
  813. {
  814. var rowIdx = table.Rows.IndexOf(view.Row);
  815. if (rowIdx < 0)
  816. {
  817. row = null;
  818. }
  819. else
  820. {
  821. row = Parent.Parent.Data.Rows[rowIdx];
  822. }
  823. }
  824. else
  825. {
  826. row = null;
  827. }
  828. if (row is null) return null;
  829. return TemplateGenerator.CreateDataTemplate(() =>
  830. {
  831. return DataTemplate(row);
  832. });
  833. }
  834. }
  835. private void ApplyFilterStyle(GridColumn column, bool filtering, bool isactioncolumn)
  836. {
  837. var filterstyle = new Style();
  838. if (filtering)
  839. {
  840. filterstyle.Setters.Add(new Setter(Control.BackgroundProperty, DynamicGridUtils.FilterBackground));
  841. column.ImmediateUpdateColumnFilter = true;
  842. column.ColumnFilter = ColumnFilter.Value;
  843. column.FilterRowCondition = FilterRowCondition.Contains;
  844. column.FilterRowOptionsVisibility = Visibility.Collapsed;
  845. column.AllowBlankFilters = true;
  846. column.AllowSorting = isactioncolumn
  847. ? false
  848. : Parent.CanSort();
  849. }
  850. else
  851. {
  852. filterstyle.Setters.Add(new Setter(Control.BackgroundProperty, new SolidColorBrush(Colors.Gainsboro)));
  853. filterstyle.Setters.Add(new Setter(Control.IsEnabledProperty, false));
  854. column.ColumnFilter = ColumnFilter.Value;
  855. column.AllowFiltering = false;
  856. column.AllowSorting = false;
  857. column.FilterRowEditorType = "TextBox";
  858. column.FilterRowOptionsVisibility = Visibility.Collapsed;
  859. }
  860. column.FilterRowCellStyle = filterstyle;
  861. }
  862. private void LoadDataColumns(DynamicGridColumns columns)
  863. {
  864. foreach (var column in columns)
  865. {
  866. if (this.CreateEditorColumn(column, out var newcol, out var prop))
  867. {
  868. newcol.GetEntity = () => _editingObject.Object;
  869. newcol.EntityChanged += DoEntityChanged;
  870. if (!newcol.VariableHeight)
  871. gridRowResizingOptions.ExcludeColumns.Add(newcol.MappingName);
  872. var newColumn = newcol.CreateGridColumn();
  873. newColumn.AllowEditing = newcol.Editable && Parent.IsDirectEditMode();
  874. var summary = newcol.Summary();
  875. if (summary != null)
  876. Summaries.Add(summary);
  877. ApplyFilterStyle(newColumn, newcol.Filtered, false);
  878. var headstyle = new Style(typeof(GridHeaderCellControl));
  879. headstyle.Setters.Add(new Setter(Control.BackgroundProperty, new SolidColorBrush(Colors.Gainsboro)));
  880. headstyle.Setters.Add(new Setter(Control.ForegroundProperty, new SolidColorBrush(Colors.Black)));
  881. headstyle.Setters.Add(new Setter(Control.FontSizeProperty, 12D));
  882. newColumn.HeaderStyle = headstyle;
  883. var cellstyle = new Style();
  884. if (Parent.IsDirectEditMode())
  885. {
  886. if (prop.Editor is null || !prop.Editor.Editable.IsDirectEditable())
  887. {
  888. cellstyle.Setters.Add(new Setter(Control.BackgroundProperty,
  889. new Binding()
  890. {
  891. Path = new PropertyPath("."), Converter = CellBackgroundConverter,
  892. ConverterParameter = new DynamicGridCellStyleParameters(column,new SolidColorBrush(Colors.WhiteSmoke))
  893. }));
  894. newColumn.AllowEditing = false;
  895. }
  896. else
  897. {
  898. cellstyle.Setters.Add(new Setter(Control.BackgroundProperty,
  899. new Binding()
  900. {
  901. Path = new PropertyPath("."), Converter = CellBackgroundConverter,
  902. ConverterParameter = new DynamicGridCellStyleParameters(column,new SolidColorBrush(Colors.LightYellow))
  903. }));
  904. newColumn.AllowEditing = true;
  905. }
  906. cellstyle.Setters.Add(new Setter(Control.ForegroundProperty, new SolidColorBrush(Colors.Black)));
  907. newColumn.CellStyle = cellstyle;
  908. }
  909. else
  910. {
  911. cellstyle.Setters.Add(new Setter(Control.BackgroundProperty,
  912. new Binding()
  913. {
  914. Path = new PropertyPath("."), Converter = CellBackgroundConverter,
  915. ConverterParameter = new DynamicGridCellStyleParameters(column,DependencyProperty.UnsetValue)
  916. }));
  917. cellstyle.Setters.Add(new Setter(Control.ForegroundProperty,
  918. new Binding()
  919. {
  920. Converter = CellForegroundConverter,
  921. ConverterParameter = new DynamicGridCellStyleParameters(column,DependencyProperty.UnsetValue)
  922. }));
  923. cellstyle.Setters.Add(new Setter(Control.FontSizeProperty,
  924. new Binding()
  925. {
  926. Converter = CellFontSizeConverter,
  927. ConverterParameter = new DynamicGridCellStyleParameters(column,DependencyProperty.UnsetValue)
  928. }));
  929. cellstyle.Setters.Add(new Setter(Control.FontStyleProperty,
  930. new Binding()
  931. {
  932. Converter = CellFontStyleConverter,
  933. ConverterParameter = new DynamicGridCellStyleParameters(column,DependencyProperty.UnsetValue)
  934. }));
  935. cellstyle.Setters.Add(new Setter(Control.FontWeightProperty,
  936. new Binding()
  937. {
  938. Converter = CellFontWeightConverter,
  939. ConverterParameter = new DynamicGridCellStyleParameters(column,DependencyProperty.UnsetValue)
  940. }));
  941. newColumn.CellStyle = cellstyle;
  942. }
  943. DataGrid.Columns.Add(newColumn);
  944. ColumnList.Add(column);
  945. foreach (var extra in newcol.ExtraColumns)
  946. Parent.AddHiddenColumn(extra);
  947. }
  948. }
  949. }
  950. private void LoadSummaries()
  951. {
  952. if (Summaries.Any())
  953. {
  954. DataGrid.CellRenderers.Remove("TableSummary");
  955. DataGrid.CellRenderers.Add("TableSummary", new DynamicGridAggregateRenderer());
  956. DataGrid.TableSummaryRows.Add(new GridTableSummaryRow
  957. {
  958. ShowSummaryInRow = false,
  959. Position = TableSummaryRowPosition.Bottom,
  960. SummaryColumns = Summaries
  961. });
  962. }
  963. }
  964. public void RefreshColumns(DynamicGridColumns columns, DynamicActionColumns actionColumns, DynamicGridColumnGroupings groupings)
  965. {
  966. // Yo, please don't remove this.
  967. // 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
  968. // 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(),
  969. // and thus some mega problems (perhaps even exceptions within Syncfusion) were occurring, and this seems to fix it.
  970. // I don't pretend to know why it works; this is probably the strangest problem I've ever come across.
  971. DataGrid.ItemsSource = null;
  972. DataGrid.Columns.Suspend();
  973. ColumnList.Clear();
  974. DataGrid.Columns.Clear();
  975. DataGrid.TableSummaryRows.Clear();
  976. gridRowResizingOptions.ExcludeColumns = new List<string>();
  977. ActionColumns = actionColumns.ToList();
  978. Summaries.Clear();
  979. LoadActionColumns(DynamicActionColumnPosition.Start);
  980. LoadDataColumns(columns);
  981. LoadActionColumns(DynamicActionColumnPosition.End);
  982. LoadSummaries();
  983. LoadStackedHeaders(groupings);
  984. DataGrid.Columns.Resume();
  985. DataGrid.RefreshColumns();
  986. foreach (var key in _filterpredicates.Keys.ToArray())
  987. if (DataGrid.Columns.Any(x => string.Equals(x.MappingName, key)))
  988. {
  989. var predicates = Serialization.Deserialize<List<FilterPredicate>>(_filterpredicates[key]);
  990. foreach (var predicate in predicates)
  991. {
  992. DataGrid.Columns[key].FilterPredicates.Add(predicate);
  993. DataGrid.Columns[key].FilteredFrom = FilteredFrom.FilterRow;
  994. }
  995. }
  996. else
  997. {
  998. _filterpredicates.Remove(key);
  999. }
  1000. ResizeColumns(DataGrid, DataGrid.ActualWidth - 2, DataGrid.ActualHeight - 2);
  1001. }
  1002. #endregion
  1003. #region Data
  1004. private bool _invalidating = false;
  1005. public void BeforeRefresh()
  1006. {
  1007. DataGrid.SelectionForegroundBrush = GetCellSelectionForegroundBrush();
  1008. DataGrid.RowSelectionBrush = GetCellSelectionBackgroundBrush();
  1009. }
  1010. public void RefreshData(CoreTable data)
  1011. {
  1012. var defaults = new List<object?>();
  1013. var result = new DataTable();
  1014. foreach (var column in data.Columns)
  1015. {
  1016. var colname = column.ColumnName.Replace('.', '_');
  1017. if (!result.Columns.Contains(colname))
  1018. {
  1019. result.Columns.Add(colname, column.DataType);
  1020. if (!Parent.IsDirectEditMode())
  1021. defaults.Add(column.DataType.GetDefault());
  1022. }
  1023. }
  1024. for (var i = 0; i < ActionColumns.Count; i++)
  1025. result.Columns.Add(string.Format("ActionColumn{0}", i),
  1026. ActionColumns[i] is DynamicImageColumn
  1027. ? typeof(BitmapImage)
  1028. : typeof(String)
  1029. );
  1030. foreach (var row in data.Rows)
  1031. {
  1032. var newrow = result.NewRow();
  1033. CoreRowToDataRow(newrow, row, defaults);
  1034. result.Rows.Add(newrow);
  1035. }
  1036. result.ColumnChanged += Result_ColumnChanged;
  1037. //int rowIndex = DataGrid.SelectionController.CurrentCellManager.CurrentRowColumnIndex.RowIndex;
  1038. //int columnIndex = DataGrid.SelectionController.CurrentCellManager.CurrentRowColumnIndex.ColumnIndex;
  1039. //int scrollRowIndex = DataGrid.GetVisualContainer().ScrollRows.LastBodyVisibleLineIndex;
  1040. DataGrid.ItemsSource = result;
  1041. //this.DataGrid.ScrollInView(new Syncfusion.UI.Xaml.ScrollAxis.RowColumnIndex(scrollRowIndex, columnIndex));
  1042. ResizeColumns(DataGrid, DataGrid.ActualWidth - 1, DataGrid.ActualHeight);
  1043. UpdateRecordCount();
  1044. }
  1045. public void InvalidateRow(CoreRow row)
  1046. {
  1047. var table = DataGridItems;
  1048. if(table is null)
  1049. {
  1050. return;
  1051. }
  1052. _invalidating = true;
  1053. var rowdata = new List<object?>(row.Values);
  1054. foreach (var ac in ActionColumns)
  1055. rowdata.Add(ac.Data(row));
  1056. var datarow = DataGridItems.Rows[row.Index];
  1057. for (var i = 0; i < rowdata.Count; i++)
  1058. datarow[i] = rowdata[i] ?? DBNull.Value;
  1059. _invalidating = false;
  1060. //datarow.ItemArray = rowdata.ToArray();
  1061. }
  1062. private void CoreRowToDataRow(DataRow newrow, CoreRow row, List<object?> defaults)
  1063. {
  1064. var rowdata = new List<object?>(row.Values);
  1065. foreach (var ac in ActionColumns)
  1066. rowdata.Add(ac.Data(row));
  1067. try
  1068. {
  1069. var data = ProcessRow(rowdata, defaults).ToArray();
  1070. newrow.ItemArray = data;
  1071. }
  1072. catch (Exception)
  1073. {
  1074. throw;
  1075. }
  1076. }
  1077. private static IEnumerable<object?> ProcessRow(List<object?> values, List<object?> defaults)
  1078. {
  1079. if (defaults == null || !defaults.Any())
  1080. return values;
  1081. var result = new List<object?>();
  1082. for (var i = 0; i < values.Count; i++)
  1083. {
  1084. var value = values[i];
  1085. var defaultvalue = i < defaults.Count ? defaults[i] : null;
  1086. result.Add(value == null || (value.Equals(defaultvalue) && !value.GetType().IsEnum) ? null : value);
  1087. }
  1088. return result;
  1089. }
  1090. #endregion
  1091. #region Direct Edit
  1092. private bool bChanged;
  1093. private class DirectEditingObject
  1094. {
  1095. public T Object { get; set; }
  1096. public CoreRow Row { get; set; }
  1097. public DataRow? DataRow { get; set; }
  1098. public DirectEditingObject(T obj, CoreRow row, DataRow? dataRow)
  1099. {
  1100. Object = obj;
  1101. Row = row;
  1102. DataRow = dataRow;
  1103. }
  1104. }
  1105. private DirectEditingObject? _editingObject;
  1106. private DirectEditingObject EnsureEditingObject(CoreRow row)
  1107. {
  1108. _editingObject ??= new(Parent.LoadItem(row), row, DataGridItems?.Rows[row.Index]);
  1109. return _editingObject;
  1110. }
  1111. private DataRow? GetDataRow(CoreRow row)
  1112. {
  1113. return DataGridItems?.Rows[row.Index];
  1114. }
  1115. void IDynamicGridUIComponent<T>.UpdateCell(CoreRow row, string column, object? value)
  1116. {
  1117. var dataRow = GetDataRow(row);
  1118. var datacolname = column.Replace(".", "_");
  1119. if(dataRow is not null)
  1120. {
  1121. dataRow[datacolname] = value ?? DBNull.Value;
  1122. }
  1123. }
  1124. void IDynamicGridUIComponent<T>.UpdateRow(CoreRow row)
  1125. {
  1126. var dataRow = GetDataRow(row);
  1127. if(dataRow is not null)
  1128. {
  1129. foreach(var (key, value) in row)
  1130. {
  1131. var datacolname = key.Replace(".", "_");
  1132. var dataValue = dataRow[datacolname];
  1133. if (!Equals(dataValue, value) && !(value is null && dataValue == DBNull.Value))
  1134. {
  1135. dataRow[datacolname] = value ?? DBNull.Value;
  1136. }
  1137. }
  1138. for (var i = 0; i < ActionColumns.Count; i++)
  1139. dataRow[$"ActionColumn{i}"] = ActionColumns[i].Data(row);
  1140. }
  1141. }
  1142. private void DoEntityChanged(IDynamicColumnBase column, DynamicColumnEntityChangedEventArgs args)
  1143. {
  1144. if (_editingObject is null) return;
  1145. Parent.EntityChanged(_editingObject.Object, _editingObject.Row, args.ColumnName, args.Changes);
  1146. }
  1147. private void UpdateData(string column, Dictionary<CoreColumn, object?> updates)
  1148. {
  1149. if (_editingObject is null)
  1150. return;
  1151. var coreRow = _editingObject.Row;
  1152. Parent.UpdateData(_editingObject.Object, coreRow, column, updates);
  1153. }
  1154. private void UpdateData(int rowIndex, int columnIndex)
  1155. {
  1156. var table = DataGridItems;
  1157. if (table is null)
  1158. return;
  1159. if (GetColumn(columnIndex) is DynamicGridColumn gridcol)
  1160. {
  1161. var datacol = Parent.Data.Columns.FirstOrDefault(x => x.ColumnName.Equals(gridcol.ColumnName));
  1162. if (datacol != null)
  1163. {
  1164. var datacolindex = Parent.Data.Columns.IndexOf(datacol);
  1165. var value = table.Rows[rowIndex][datacolindex];
  1166. if (value is DBNull)
  1167. value = CoreUtils.GetDefault(datacol.DataType);
  1168. UpdateData(datacol.ColumnName, new Dictionary<CoreColumn, object?>() { { datacol, value } });
  1169. }
  1170. }
  1171. }
  1172. private void DataGrid_CurrentCellBeginEdit(object? sender, CurrentCellBeginEditEventArgs e)
  1173. {
  1174. var table = DataGridItems;
  1175. var row = GetRowFromIndex(e.RowColumnIndex.RowIndex);
  1176. if (table is null || row is null)
  1177. return;
  1178. EnsureEditingObject(row);
  1179. var column = DataGrid.Columns[e.RowColumnIndex.ColumnIndex] as GridComboBoxColumn;
  1180. if (column != null && column.ItemsSource == null)
  1181. {
  1182. var colname = column.MappingName;
  1183. var colno = table.Columns.IndexOf(colname);
  1184. var property = Parent.Data.Columns[colno].ColumnName;
  1185. var prop = CoreUtils.GetProperty(typeof(T), property);
  1186. var editor = prop.GetEditor();
  1187. if (editor is ILookupEditor lookupEditor)
  1188. {
  1189. if (!Lookups.ContainsKey(property))
  1190. Lookups[property] = lookupEditor.Values(typeof(T), property);
  1191. var combo = column;
  1192. combo.ItemsSource = Lookups[property].ToDictionary(Lookups[property].Columns[0].ColumnName, "Display");
  1193. combo.SelectedValuePath = "Key";
  1194. combo.DisplayMemberPath = "Value";
  1195. }
  1196. }
  1197. bChanged = false;
  1198. }
  1199. private void Result_ColumnChanged(object sender, DataColumnChangeEventArgs e)
  1200. {
  1201. if (_invalidating) return;
  1202. if (sender is not DataTable table) return;
  1203. var rowIdx = table.Rows.IndexOf(e.Row);
  1204. if (rowIdx < 0)
  1205. return;
  1206. var row = Parent.Data.Rows[rowIdx];
  1207. var colIdx = table.Columns.IndexOf(e.Column);
  1208. if (colIdx < 0 || colIdx >= Parent.Data.Columns.Count)
  1209. return;
  1210. var data = Parent.Data;
  1211. var dataCol = Parent.Data.Columns[colIdx];
  1212. var col = ColumnList.OfType<DynamicGridColumn>()
  1213. .FirstOrDefault(x => x.ColumnName.Equals(dataCol.ColumnName));
  1214. if (col is null)
  1215. return;
  1216. if (col is DynamicGridCheckBoxColumn<T>)
  1217. {
  1218. EnsureEditingObject(row);
  1219. if(_editingObject is not null)
  1220. {
  1221. var value = e.Row[e.Column!];
  1222. if (value is DBNull)
  1223. value = CoreUtils.GetDefault(dataCol.DataType);
  1224. _invalidating = true;
  1225. UpdateData(dataCol.ColumnName, new Dictionary<CoreColumn, object?>() { { dataCol, value } });
  1226. _invalidating = false;
  1227. }
  1228. _editingObject = null;
  1229. }
  1230. if (_editingObject is not null)
  1231. bChanged = true;
  1232. }
  1233. private void DataGrid_CurrentCellDropDownSelectionChanged(object? sender,
  1234. CurrentCellDropDownSelectionChangedEventArgs e)
  1235. {
  1236. var row = GetRowFromIndex(e.RowColumnIndex.RowIndex);
  1237. if (row is null)
  1238. return;
  1239. EnsureEditingObject(row);
  1240. if ((_editingObject is not null) && (e.SelectedItem is Tuple<object?, string> tuple))
  1241. {
  1242. var mappedname = DataGrid.Columns[e.RowColumnIndex.ColumnIndex].MappingName;
  1243. var colno = DataGridItems.Columns.IndexOf(mappedname);
  1244. var corecol = Parent.Data.Columns[colno].ColumnName;
  1245. var updates = new Dictionary<CoreColumn, object?>();
  1246. var prefix = String.Join(".", corecol.Split(".").Reverse().Skip(1).Reverse());
  1247. var field = corecol.Split(".").Last();
  1248. var prop = CoreUtils.GetProperty(typeof(T), corecol);
  1249. if (prop.GetEditor() is ILookupEditor editor)
  1250. {
  1251. var data = editor.Values(typeof(T), corecol);
  1252. var lookuprow = data.Rows.FirstOrDefault(r => Equals(r[field], tuple.Item1))
  1253. ?? data.NewRow(true);
  1254. foreach (CoreColumn lookupcol in data.Columns)
  1255. {
  1256. var columnname = String.IsNullOrWhiteSpace(prefix)
  1257. ? lookupcol.ColumnName
  1258. : String.Join(".", prefix, lookupcol.ColumnName);
  1259. var updatecol = Parent.Data.Columns.FirstOrDefault(x => String.Equals(x.ColumnName, columnname));
  1260. if (updatecol != null)
  1261. updates[updatecol] = lookuprow[lookupcol.ColumnName];
  1262. }
  1263. UpdateData(corecol, updates);
  1264. bChanged = true;
  1265. }
  1266. }
  1267. }
  1268. private void DataGrid_CurrentCellEndEdit(object? sender, CurrentCellEndEditEventArgs e)
  1269. {
  1270. if (_editingObject is not null && bChanged)
  1271. {
  1272. UpdateData(_editingObject.Row.Index, e.RowColumnIndex.ColumnIndex);
  1273. }
  1274. if (bChanged)
  1275. Parent.DoChanged();
  1276. bChanged = false;
  1277. _editingObject = null;
  1278. // 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
  1279. // editing the filter row. It seems that this causes Syncfusion to commit the filter predicates internally, which means that after leaving a
  1280. // filter row cell, the filter remained even once it was cleared, meaning a refresh was necessary to get the data back.
  1281. // I've tested on Bills to see if editing works with this empty, and it seems so.
  1282. //DataGridItems?.AcceptChanges();
  1283. }
  1284. private void DataGrid_PreviewKeyUp(object sender, KeyEventArgs e)
  1285. {
  1286. if (e.Key == Key.OemPeriod)
  1287. {
  1288. var editor = e.OriginalSource as TimeSpanEdit;
  1289. if (editor != null && editor.SelectionStart < 2) editor.SelectionStart = 3;
  1290. }
  1291. else if (e.Key == Key.Tab)
  1292. {
  1293. if (Parent.IsDirectEditMode())
  1294. {
  1295. DataGrid.SelectionController.CurrentCellManager.EndEdit();
  1296. DataGrid.MoveFocus(new TraversalRequest(FocusNavigationDirection.Right));
  1297. DataGrid.SelectionController.CurrentCellManager.BeginEdit();
  1298. e.Handled = true;
  1299. }
  1300. }
  1301. }
  1302. #endregion
  1303. #region Drag + Drop
  1304. private void DataGrid_DragOver(object sender, DragEventArgs e)
  1305. {
  1306. Parent.DragOver(sender, e);
  1307. }
  1308. private void DataGrid_Drop(object sender, DragEventArgs e)
  1309. {
  1310. Parent.Drop(sender, e);
  1311. }
  1312. private void RowDragDropController_DragStart(object? sender, GridRowDragStartEventArgs e)
  1313. {
  1314. var rows = e.DraggingRecords.Select(record =>
  1315. {
  1316. var rowIndex = DataGrid.ResolveToRowIndex(record);
  1317. return GetRowFromIndex(rowIndex);
  1318. }).NotNull().ToArray();
  1319. Parent.DragStart(sender, rows);
  1320. }
  1321. #endregion
  1322. }