DynamicGridGridUIComponent.cs 63 KB

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