DynamicGridGridUIComponent.cs 65 KB

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