DynamicGridGridUIComponent.cs 64 KB

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