DynamicGrid.cs 80 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.Collections.ObjectModel;
  5. using System.ComponentModel;
  6. using System.Data;
  7. using System.Diagnostics;
  8. using System.Diagnostics.CodeAnalysis;
  9. using System.Globalization;
  10. using System.Linq;
  11. using System.Linq.Expressions;
  12. using System.Threading.Tasks;
  13. using System.Windows;
  14. using System.Windows.Controls;
  15. using System.Windows.Data;
  16. using System.Windows.Forms.VisualStyles;
  17. using System.Windows.Input;
  18. using System.Windows.Media;
  19. using System.Windows.Media.Animation;
  20. using System.Windows.Media.Imaging;
  21. using System.Windows.Threading;
  22. using InABox.Clients;
  23. using InABox.Core;
  24. using InABox.Wpf;
  25. using InABox.WPF;
  26. using javax.xml.crypto;
  27. using Microsoft.CodeAnalysis.CSharp.Syntax;
  28. using Microsoft.Xaml.Behaviors;
  29. using Syncfusion.Data;
  30. using Syncfusion.DocIO.ReaderWriter.DataStreamParser.Escher;
  31. using Syncfusion.UI.Xaml.Grid;
  32. using Syncfusion.UI.Xaml.Grid.Cells;
  33. using Syncfusion.UI.Xaml.Grid.Helpers;
  34. using Syncfusion.Windows.Shared;
  35. using static InABox.DynamicGrid.IDynamicGrid;
  36. using Brush = System.Windows.Media.Brush;
  37. using Color = System.Drawing.Color;
  38. using Columns = InABox.Core.Columns;
  39. using DataColumn = System.Data.DataColumn;
  40. using DataRow = System.Data.DataRow;
  41. using FilterElement = Syncfusion.UI.Xaml.Grid.FilterElement;
  42. using FontStyle = System.Windows.FontStyle;
  43. using GridCellToolTipOpeningEventArgs = Syncfusion.UI.Xaml.Grid.GridCellToolTipOpeningEventArgs;
  44. using GridFilterEventArgs = Syncfusion.UI.Xaml.Grid.GridFilterEventArgs;
  45. using GridSelectionMode = Syncfusion.UI.Xaml.Grid.GridSelectionMode;
  46. using Image = System.Windows.Controls.Image;
  47. using RowColumnIndex = Syncfusion.UI.Xaml.ScrollAxis.RowColumnIndex;
  48. using SolidColorBrush = System.Windows.Media.SolidColorBrush;
  49. using String = System.String;
  50. using VerticalAlignment = System.Windows.VerticalAlignment;
  51. using VirtualizingCellsControl = Syncfusion.UI.Xaml.Grid.VirtualizingCellsControl;
  52. namespace InABox.DynamicGrid;
  53. public class DynamicGridRowStyle : DynamicGridStyle<VirtualizingCellsControl>
  54. {
  55. public DynamicGridRowStyle() : base(null)
  56. {
  57. }
  58. public DynamicGridRowStyle(IDynamicGridStyle source) : base(source)
  59. {
  60. }
  61. public override DependencyProperty FontSizeProperty => Control.FontSizeProperty;
  62. public override DependencyProperty FontStyleProperty => Control.FontStyleProperty;
  63. public override DependencyProperty FontWeightProperty => Control.FontWeightProperty;
  64. public override DependencyProperty BackgroundProperty => Control.BackgroundProperty;
  65. public override DependencyProperty ForegroundProperty => Control.ForegroundProperty;
  66. }
  67. public class DynamicGridCellStyle : DynamicGridStyle<Control>
  68. {
  69. public DynamicGridCellStyle() : base(null)
  70. {
  71. }
  72. public DynamicGridCellStyle(IDynamicGridStyle source) : base(source)
  73. {
  74. }
  75. public override DependencyProperty FontSizeProperty => Control.FontSizeProperty;
  76. public override DependencyProperty FontStyleProperty => Control.FontStyleProperty;
  77. public override DependencyProperty FontWeightProperty => Control.FontWeightProperty;
  78. public override DependencyProperty BackgroundProperty => Control.BackgroundProperty;
  79. public override DependencyProperty ForegroundProperty => Control.ForegroundProperty;
  80. }
  81. public class GridSelectionControllerExt : GridSelectionController
  82. {
  83. public GridSelectionControllerExt(SfDataGrid datagrid)
  84. : base(datagrid)
  85. {
  86. }
  87. protected override void ProcessSelectedItemChanged(SelectionPropertyChangedHandlerArgs handle)
  88. {
  89. base.ProcessSelectedItemChanged(handle);
  90. if (handle.NewValue != null)
  91. {
  92. //this.DataGrid.ScrollInView(this.CurrentCellManager.CurrentRowColumnIndex);
  93. //int rowIndex = this.CurrentCellManager.CurrentRowColumnIndex.RowIndex;
  94. var columnIndex = CurrentCellManager.CurrentRowColumnIndex.ColumnIndex;
  95. var scrollRowIndex = DataGrid.GetVisualContainer().ScrollRows.LastBodyVisibleLineIndex;
  96. DataGrid.ScrollInView(new RowColumnIndex(scrollRowIndex, columnIndex));
  97. }
  98. }
  99. }
  100. public class DynamicGridSummaryStyleSelector : StyleSelector
  101. {
  102. private readonly IDynamicGrid _grid;
  103. public DynamicGridSummaryStyleSelector(IDynamicGrid grid)
  104. {
  105. _grid = grid;
  106. }
  107. public override Style SelectStyle(object item, DependencyObject container)
  108. {
  109. var vcol = ((GridTableSummaryCell)container).ColumnBase.ColumnIndex;
  110. var col = vcol > -1 && vcol < _grid.VisibleColumns.Count ? _grid.VisibleColumns[vcol] : null;
  111. var style = new Style(typeof(GridTableSummaryCell));
  112. style.Setters.Add(new Setter(Control.BackgroundProperty, new SolidColorBrush(Colors.Gainsboro)));
  113. style.Setters.Add(new Setter(Control.ForegroundProperty, new SolidColorBrush(Colors.Black)));
  114. style.Setters.Add(new Setter(Control.HorizontalContentAlignmentProperty,
  115. col != null ? col.HorizontalAlignment(typeof(double)) : HorizontalAlignment.Right));
  116. style.Setters.Add(new Setter(Control.BorderBrushProperty, new SolidColorBrush(Colors.Gray)));
  117. style.Setters.Add(new Setter(Control.BorderThicknessProperty, new Thickness(0, 0, 0.75, 0)));
  118. style.Setters.Add(new Setter(Control.FontSizeProperty, 12D));
  119. style.Setters.Add(new Setter(Control.FontWeightProperty, FontWeights.DemiBold));
  120. return style;
  121. }
  122. }
  123. // Used to render boolean columns (the default "false" value shows what appears to be an intermediate state, which is ugly
  124. // This should show nothing for false, and a tick in a box for true
  125. public class BoolToImageConverter : AbstractConverter<bool,ImageSource>
  126. {
  127. public ImageSource TrueValue { get; set; }
  128. public ImageSource FalseValue { get; set; }
  129. public BoolToImageConverter()
  130. {
  131. TrueValue = Wpf.Resources.Bullet_Tick.AsBitmapImage();
  132. }
  133. public override ImageSource Convert(bool value)
  134. {
  135. return value ? TrueValue : FalseValue;
  136. }
  137. public override bool Deconvert(ImageSource value)
  138. {
  139. return ImageUtils.IsEqual(value as BitmapImage,TrueValue as BitmapImage);
  140. }
  141. }
  142. public class StringToColorImageConverter : IValueConverter
  143. {
  144. private readonly int _height = 50;
  145. private readonly int _width = 25;
  146. private readonly Dictionary<string, BitmapImage> cache = new();
  147. public StringToColorImageConverter(int width, int height)
  148. {
  149. _width = width;
  150. _height = height;
  151. }
  152. public object? Convert(object value, Type targetType, object parameter, CultureInfo culture)
  153. {
  154. <<<<<<< HEAD
  155. var str = value?.ToString();
  156. if (str is null)
  157. =======
  158. public GridSelectionControllerExt(SfDataGrid datagrid)
  159. : base(datagrid)
  160. {
  161. }
  162. protected override void ProcessSelectedItemChanged(SelectionPropertyChangedHandlerArgs handle)
  163. {
  164. base.ProcessSelectedItemChanged(handle);
  165. if (handle.NewValue != null)
  166. {
  167. //this.DataGrid.ScrollInView(this.CurrentCellManager.CurrentRowColumnIndex);
  168. //int rowIndex = this.CurrentCellManager.CurrentRowColumnIndex.RowIndex;
  169. var columnIndex = CurrentCellManager.CurrentRowColumnIndex.ColumnIndex;
  170. var scrollRowIndex = DataGrid.GetVisualContainer().ScrollRows.LastBodyVisibleLineIndex;
  171. DataGrid.ScrollInView(new RowColumnIndex(scrollRowIndex, columnIndex));
  172. }
  173. }
  174. }
  175. public class DynamicGridSummaryStyleSelector : StyleSelector
  176. {
  177. private readonly IDynamicGrid _grid;
  178. public DynamicGridSummaryStyleSelector(IDynamicGrid grid)
  179. {
  180. _grid = grid;
  181. }
  182. public override Style SelectStyle(object item, DependencyObject container)
  183. {
  184. var vcol = ((GridTableSummaryCell)container).ColumnBase.ColumnIndex;
  185. var col = vcol > -1 && vcol < _grid.VisibleColumns.Count ? _grid.VisibleColumns[vcol] : null;
  186. var style = new Style(typeof(GridTableSummaryCell));
  187. style.Setters.Add(new Setter(Control.BackgroundProperty, new SolidColorBrush(Colors.Gainsboro)));
  188. style.Setters.Add(new Setter(Control.ForegroundProperty, new SolidColorBrush(Colors.Black)));
  189. style.Setters.Add(new Setter(Control.HorizontalContentAlignmentProperty,
  190. col != null ? col.HorizontalAlignment(typeof(double)) : HorizontalAlignment.Right));
  191. style.Setters.Add(new Setter(Control.BorderBrushProperty, new SolidColorBrush(Colors.Gray)));
  192. style.Setters.Add(new Setter(Control.BorderThicknessProperty, new Thickness(0, 0, 0.75, 0)));
  193. style.Setters.Add(new Setter(Control.FontSizeProperty, 12D));
  194. style.Setters.Add(new Setter(Control.FontWeightProperty, FontWeights.DemiBold));
  195. return style;
  196. }
  197. }
  198. // Used to render boolean columns (the default "false" value shows what appears to be an intermediate state, which is ugly
  199. // This should show nothing for false, and a tick in a box for true
  200. public class BoolToImageConverter : AbstractConverter<bool,ImageSource>
  201. {
  202. public ImageSource TrueValue { get; set; }
  203. public ImageSource FalseValue { get; set; }
  204. public BoolToImageConverter()
  205. {
  206. TrueValue = Wpf.Resources.Bullet_Tick.AsBitmapImage();
  207. }
  208. public override ImageSource Convert(bool value)
  209. {
  210. return value ? TrueValue : FalseValue;
  211. }
  212. public override bool Deconvert(ImageSource value)
  213. {
  214. return ImageUtils.IsEqual(value as BitmapImage,TrueValue as BitmapImage);
  215. }
  216. }
  217. public class StringToColorImageConverter : IValueConverter
  218. {
  219. private readonly int _height = 50;
  220. private readonly int _width = 25;
  221. private readonly Dictionary<string, BitmapImage> cache = new();
  222. public StringToColorImageConverter(int width, int height)
  223. {
  224. _width = width;
  225. _height = height;
  226. }
  227. public object? Convert(object value, Type targetType, object parameter, CultureInfo culture)
  228. {
  229. var str = value?.ToString();
  230. if (str is null)
  231. return null;
  232. var colorcode = str.TrimStart('#');
  233. if (!cache.ContainsKey(colorcode))
  234. {
  235. var col = ImageUtils.StringToColor(colorcode);
  236. var bmp = ImageUtils.BitmapFromColor(col, _width, _height, Color.Black);
  237. cache[colorcode] = bmp.AsBitmapImage();
  238. }
  239. var result = cache[colorcode];
  240. return result;
  241. }
  242. public object? ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
  243. {
  244. >>>>>>> origin/frank
  245. return null;
  246. var colorcode = str.TrimStart('#');
  247. if (!cache.ContainsKey(colorcode))
  248. {
  249. var col = ImageUtils.StringToColor(colorcode);
  250. var bmp = ImageUtils.BitmapFromColor(col, _width, _height, Color.Black);
  251. cache[colorcode] = bmp.AsBitmapImage();
  252. }
  253. var result = cache[colorcode];
  254. return result;
  255. }
  256. public object? ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
  257. {
  258. return null;
  259. }
  260. }
  261. public class StringArrayConverter : IValueConverter
  262. {
  263. object? IValueConverter.Convert(object value, Type targetType, object parameter, CultureInfo culture)
  264. {
  265. if (value is string[] strArray)
  266. {
  267. return string.Join("\n", strArray);
  268. }
  269. Logger.Send(LogType.Error, "", $"Attempt to convert an object which is not a string array: {value}.");
  270. return null;
  271. }
  272. object IValueConverter.ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
  273. {
  274. return value;
  275. }
  276. }
  277. [Serializable]
  278. class DynamicGridDragFormat
  279. {
  280. private string entity;
  281. public DataTable Table { get; set; }
  282. public Type Entity { get => CoreUtils.GetEntity(entity); set => entity = value.EntityName(); }
  283. public DynamicGridDragFormat(DataTable table, Type entity)
  284. {
  285. Table = table;
  286. Entity = entity;
  287. }
  288. }
  289. public abstract class DynamicGrid : ContentControl
  290. {
  291. public static readonly DependencyProperty UseWaitCursorProperty =
  292. DependencyProperty.Register(nameof(UseWaitCursor), typeof(bool), typeof(DynamicGrid<>));
  293. public bool UseWaitCursor
  294. {
  295. get => (bool)GetValue(UseWaitCursorProperty);
  296. set => SetValue(UseWaitCursorProperty, value);
  297. }
  298. }
  299. public abstract class DynamicGrid<T> : DynamicGrid, IDynamicGridUIComponentParent<T>, IDynamicGrid<T>
  300. where T : BaseObject, new()
  301. {
  302. protected enum ClipAction
  303. {
  304. Cut,
  305. Copy
  306. }
  307. private IDynamicGridUIComponent<T> UIComponent { get; set; }
  308. private UIElement? _header;
  309. private readonly Button Add;
  310. public bool bRefreshing;
  311. bool IDynamicGridUIComponentParent<T>.IsRefreshing => bRefreshing;
  312. private readonly Label ClipboardSpacer;
  313. private readonly Button Copy;
  314. private readonly Label Count;
  315. private readonly Button Cut;
  316. private readonly Border Disabler;
  317. private readonly Button Delete;
  318. private readonly DockPanel Docker;
  319. private readonly DynamicRowMovementColumn? down;
  320. private readonly Button Edit;
  321. private readonly Label EditSpacer;
  322. private readonly Button Export;
  323. private readonly Label ExportSpacer;
  324. private readonly Button DuplicateBtn;
  325. private readonly Button SwitchViewBtn;
  326. private readonly Button Help;
  327. private readonly Button Import;
  328. private readonly Grid Layout;
  329. private readonly Label Loading;
  330. private DoubleAnimation LoadingFader = new DoubleAnimation(1d, 0.2d, new Duration(TimeSpan.FromSeconds(2))) { AutoReverse = true };
  331. //private readonly Button MultiEdit;
  332. private readonly Button Paste;
  333. private readonly Button Print;
  334. private readonly Label PrintSpacer;
  335. private readonly StackPanel LeftButtonStack;
  336. private readonly StackPanel RightButtonStack;
  337. private readonly DynamicRowMovementColumn? up;
  338. protected DynamicGridRowStyleSelector<T> RowStyleSelector;
  339. #region Events
  340. public event IDynamicGrid.ReconfigureEvent? OnReconfigure;
  341. public OnGetDynamicGridRowStyle? OnGetRowStyle { get; set; }
  342. public ValidateEvent<T>? OnValidate { get; set; }
  343. public event OnPrintData? OnPrintData;
  344. public event BeforeRefreshEventHandler? BeforeRefresh;
  345. public event AfterRefreshEventHandler? AfterRefresh;
  346. public event OnDefineFilter? OnDefineFilter;
  347. public event OnCreateItem? OnCreateItem;
  348. /// <summary>
  349. /// Called when an item is selected in the grid. It is not called if <see cref="IsReady"/> is not <see langword="true"/>.
  350. /// </summary>
  351. /// <remarks>
  352. /// It is unnecessary to use this if within a grid. Instead, override <see cref="SelectItems(CoreRow[]?)"/>.
  353. /// </remarks>
  354. public event SelectItemHandler? OnSelectItem;
  355. public event OnCellDoubleClick? OnCellDoubleClick;
  356. public event EventHandler? OnChanged;
  357. public delegate void BeforeSelectionEvent(CancelEventArgs cancel);
  358. public event BeforeSelectionEvent? OnBeforeSelection;
  359. public void DoChanged() => OnChanged?.Invoke(this, EventArgs.Empty);
  360. public event EditorValueChangedHandler? OnEditorValueChanged;
  361. public event OnCustomiseEditor<T>? OnCustomiseEditor;
  362. public event OnFilterRecord? OnFilterRecord;
  363. public event OnDoubleClick? OnDoubleClick;
  364. public event EntitySaveEvent? OnBeforeSave;
  365. public event EntitySaveEvent? OnAfterSave;
  366. public delegate void EditorLoaded(IDynamicEditorForm editor, T[] items);
  367. public event EditorLoaded OnEditorLoaded;
  368. public event OnLoadEditorButtons<T> OnLoadEditorButtons;
  369. public virtual event OnCustomiseColumns? OnCustomiseColumns;
  370. protected void DoCustomiseColumnsEvent(object sender, DynamicGridColumns columns) =>
  371. OnCustomiseColumns?.Invoke(sender, columns);
  372. #endregion
  373. protected DynamicGridSettings Settings { get; set; }
  374. public DynamicGrid() : base()
  375. {
  376. UseWaitCursor = true;
  377. Options = new FluentList<DynamicGridOption>();
  378. Options.OnChanged += (sender, args) =>
  379. {
  380. _hasLoadedOptions = true;
  381. OptionsChanged();
  382. };
  383. ActionColumns = new DynamicActionColumns();
  384. RowStyleSelector = GetRowStyleSelector();
  385. RowStyleSelector.GetStyle += (row, style) => GetRowStyle(row, style);
  386. IsReady = false;
  387. Data = new CoreTable();
  388. MasterColumns = new DynamicGridColumns();
  389. MasterColumns.ExtractColumns(typeof(T));
  390. HiddenColumns = new HiddenColumnsList();
  391. foreach (var column in LookupFactory.RequiredColumns<T>().ColumnNames())
  392. {
  393. AddHiddenColumn(column);
  394. }
  395. if (IsSequenced)
  396. {
  397. up = new DynamicRowMovementColumn(DynamicRowMovement.Up, SwapRows);
  398. ActionColumns.Add(up);
  399. down = new DynamicRowMovementColumn(DynamicRowMovement.Down, SwapRows);
  400. ActionColumns.Add(down);
  401. HiddenColumns.Add(x => (x as ISequenceable)!.Sequence);
  402. }
  403. VisibleColumns = new DynamicGridColumns();
  404. UIComponent = CreateUIComponent();
  405. Loading = new Label();
  406. Loading.Content = "Loading...";
  407. Loading.Foreground = new SolidColorBrush(Colors.White);
  408. Loading.VerticalContentAlignment = VerticalAlignment.Center;
  409. Loading.HorizontalContentAlignment = HorizontalAlignment.Center;
  410. Loading.Visibility = Visibility.Collapsed;
  411. Loading.SetValue(Panel.ZIndexProperty, 999);
  412. Loading.SetValue(Grid.RowProperty, 1);
  413. Loading.FontSize = 14.0F;
  414. LoadingFader.Completed += (sender, args) =>
  415. {
  416. if (Loading.Visibility == Visibility.Visible)
  417. {
  418. //Logger.Send(LogType.Information, this.GetType().EntityName().Split(".").Last(), "Loading Fader Restarting");
  419. Loading.BeginAnimation(Label.OpacityProperty, LoadingFader);
  420. }
  421. };
  422. Help = CreateButton(Wpf.Resources.help.AsBitmapImage(Color.White));
  423. Help.Margin = new Thickness(0, 2, 2, 0);
  424. Help.SetValue(DockPanel.DockProperty, Dock.Right);
  425. Help.Click += (o, e) => ShowHelp(typeof(T).Name.Split('.').Last().SplitCamelCase().Replace(" ", "_"));
  426. Add = CreateButton(Wpf.Resources.add.AsBitmapImage(Color.White));
  427. Add.Margin = new Thickness(0, 2, 2, 0);
  428. Add.Click += Add_Click;
  429. Edit = CreateButton(Wpf.Resources.pencil.AsBitmapImage(Color.White));
  430. Edit.Margin = new Thickness(0, 2, 2, 0);
  431. Edit.Click += Edit_Click;
  432. SwitchViewBtn = CreateButton(Wpf.Resources.alter.AsBitmapImage());
  433. SwitchViewBtn.Margin = new Thickness(0, 2, 2, 0);
  434. SwitchViewBtn.Click += SwitchView_Click;
  435. EditSpacer = new Label { Width = 5 };
  436. Print = CreateButton(Wpf.Resources.print.AsBitmapImage(Color.White));
  437. Print.Margin = new Thickness(0, 2, 2, 0);
  438. Print.Click += (o, e) => DoPrint(o);
  439. PrintSpacer = new Label { Width = 5 };
  440. Cut = CreateButton(Wpf.Resources.cut.AsBitmapImage(Color.White));
  441. Cut.Margin = new Thickness(0, 2, 2, 0);
  442. Cut.Click += Cut_Click;
  443. Copy = CreateButton(Wpf.Resources.copy.AsBitmapImage(Color.White));
  444. Copy.Margin = new Thickness(0, 2, 2, 0);
  445. Copy.Click += Copy_Click;
  446. Paste = CreateButton(Wpf.Resources.paste.AsBitmapImage(Color.White));
  447. Paste.Margin = new Thickness(0, 2, 2, 0);
  448. Paste.Click += Paste_Click;
  449. ClipboardSpacer = new Label { Width = 5 };
  450. Export = CreateButton(Wpf.Resources.doc_xls.AsBitmapImage(Color.White), "Export");
  451. Export.Margin = new Thickness(0, 2, 2, 0);
  452. Export.Click += Export_Click;
  453. Import = CreateButton(Wpf.Resources.doc_xls.AsBitmapImage(Color.White), "Import");
  454. Import.Margin = new Thickness(0, 2, 2, 0);
  455. Import.Click += Import_Click;
  456. ExportSpacer = new Label { Width = 5 };
  457. LeftButtonStack = new StackPanel();
  458. LeftButtonStack.Orientation = Orientation.Horizontal;
  459. LeftButtonStack.SetValue(DockPanel.DockProperty, Dock.Left);
  460. LeftButtonStack.Children.Add(Help);
  461. LeftButtonStack.Children.Add(Add);
  462. LeftButtonStack.Children.Add(Edit);
  463. LeftButtonStack.Children.Add(SwitchViewBtn);
  464. //Stack.Children.Add(MultiEdit);
  465. LeftButtonStack.Children.Add(EditSpacer);
  466. LeftButtonStack.Children.Add(Print);
  467. LeftButtonStack.Children.Add(PrintSpacer);
  468. LeftButtonStack.Children.Add(Cut);
  469. LeftButtonStack.Children.Add(Copy);
  470. LeftButtonStack.Children.Add(Paste);
  471. LeftButtonStack.Children.Add(ClipboardSpacer);
  472. LeftButtonStack.Children.Add(Export);
  473. LeftButtonStack.Children.Add(Import);
  474. LeftButtonStack.Children.Add(ExportSpacer);
  475. RightButtonStack = new StackPanel();
  476. RightButtonStack.Orientation = Orientation.Horizontal;
  477. RightButtonStack.SetValue(DockPanel.DockProperty, Dock.Right);
  478. Delete = CreateButton(Wpf.Resources.delete.AsBitmapImage(Color.White));
  479. Delete.Margin = new Thickness(2, 2, 0, 0);
  480. Delete.SetValue(DockPanel.DockProperty, Dock.Right);
  481. Delete.Click += Delete_Click;
  482. DuplicateBtn = AddButton("Duplicate", Wpf.Resources.paste.AsBitmapImage(Color.White), DoDuplicate);
  483. Count = new Label();
  484. Count.Height = 30;
  485. Count.Margin = new Thickness(0, 2, 0, 0);
  486. Count.VerticalContentAlignment = VerticalAlignment.Center;
  487. Count.HorizontalContentAlignment = HorizontalAlignment.Center;
  488. Count.SetValue(DockPanel.DockProperty, Dock.Left);
  489. Docker = new DockPanel();
  490. Docker.SetValue(Grid.RowProperty, 2);
  491. Docker.SetValue(Grid.ColumnProperty, 0);
  492. Docker.Children.Add(LeftButtonStack);
  493. Docker.Children.Add(Delete);
  494. Docker.Children.Add(RightButtonStack);
  495. Docker.Children.Add(Count);
  496. Layout = new Grid();
  497. Layout.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) });
  498. Layout.RowDefinitions.Add(new RowDefinition { Height = new GridLength(1, GridUnitType.Auto) });
  499. Layout.RowDefinitions.Add(new RowDefinition { Height = new GridLength(1, GridUnitType.Star) });
  500. Layout.RowDefinitions.Add(new RowDefinition { Height = new GridLength(1, GridUnitType.Auto) });
  501. var control = UIComponent.Control;
  502. control.SetValue(Grid.RowProperty, 1);
  503. Layout.Children.Add(control);
  504. Layout.Children.Add(Loading);
  505. Layout.Children.Add(Docker);
  506. Disabler = new Border()
  507. {
  508. BorderBrush = new SolidColorBrush(Colors.Transparent),
  509. Background = new SolidColorBrush(Colors.DimGray) { Opacity = 0.2 },
  510. Visibility = Visibility.Collapsed,
  511. };
  512. Disabler.SetValue(Canvas.ZIndexProperty, 99);
  513. Disabler.SetValue(Grid.RowSpanProperty, 3);
  514. Layout.Children.Add(Disabler);
  515. //Scroll.ApplyTemplate();
  516. Content = Layout;
  517. IsEnabledChanged += (sender, args) =>
  518. {
  519. Disabler.Visibility = Equals(args.NewValue, true)
  520. ? Visibility.Collapsed
  521. : Visibility.Visible;
  522. };
  523. Settings = LoadSettings();
  524. Init();
  525. Reconfigure();
  526. }
  527. #region IDynamicGridUIComponentParent
  528. protected virtual IDynamicGridUIComponent<T> CreateUIComponent()
  529. {
  530. return new DynamicGridGridUIComponent<T>()
  531. {
  532. Parent = this
  533. };
  534. }
  535. bool IDynamicGridUIComponentParent<T>.CanSort()
  536. {
  537. return !IsSequenced;
  538. }
  539. T IDynamicGrid<T>.LoadItem(CoreRow row) => LoadItem(row);
  540. DynamicGridRowStyleSelector<T> IDynamicGridUIComponentParent<T>.RowStyleSelector => RowStyleSelector;
  541. void IDynamicGridUIComponentParent<T>.BeforeSelection(CancelEventArgs cancel)
  542. {
  543. BeforeSelection(cancel);
  544. }
  545. void IDynamicGridUIComponentParent<T>.SelectItems(CoreRow[] rows)
  546. {
  547. SelectItems(rows);
  548. }
  549. void IDynamicGridUIComponentParent<T>.EntityChanged(T obj, CoreRow row, string changedColumn, Dictionary<string, object?> changes)
  550. => EntityChanged(obj, row, changedColumn, changes);
  551. void IDynamicGridUIComponentParent<T>.UpdateData(T obj, CoreRow row, string changedColumn, Dictionary<CoreColumn, object?> updates)
  552. {
  553. var result = new Dictionary<string, object?>();
  554. foreach (var (col, value) in updates)
  555. {
  556. UpdateRow(row, col.ColumnName, value, refresh: false);
  557. DynamicGridUtils.UpdateEditorValue(new BaseObject[] { obj }, col.ColumnName, value, result);
  558. }
  559. EntityChanged(obj, row, changedColumn, result);
  560. }
  561. void IDynamicGridUIComponentParent<T>.HandleKey(KeyEventArgs e)
  562. {
  563. if (IsSequenced)
  564. {
  565. if (e.Key == Key.X && (Keyboard.Modifiers & ModifierKeys.Control) == ModifierKeys.Control)
  566. {
  567. CutToClipBuffer();
  568. }
  569. else if (e.Key == Key.C && (Keyboard.Modifiers & ModifierKeys.Control) == ModifierKeys.Control)
  570. {
  571. CopyToClipBuffer();
  572. }
  573. else if (e.Key == Key.V && (Keyboard.Modifiers & ModifierKeys.Control) == ModifierKeys.Control)
  574. {
  575. PasteFromClipBuffer();
  576. }
  577. else if (e.Key == Key.Escape)
  578. {
  579. ResetClipBuffer();
  580. InvalidateGrid();
  581. }
  582. }
  583. }
  584. void IDynamicGridUIComponentParent<T>.DoubleClickCell(CoreRow? row, DynamicColumnBase? column)
  585. {
  586. if (OnCellDoubleClick is not null && column is DynamicGridColumn col)
  587. {
  588. var args = new DynamicGridCellClickEventArgs(row, col);
  589. OnCellDoubleClick?.Invoke(this, args);
  590. if (args.Handled)
  591. return;
  592. }
  593. if (row is not null)
  594. DoDoubleClick(this);
  595. }
  596. void IDynamicGridUIComponentParent<T>.ExecuteActionColumn(DynamicActionColumn column, CoreRow[]? rows)
  597. {
  598. var bRefresh = false;
  599. if(rows is null)
  600. {
  601. bRefresh = column.Action?.Invoke(null) ?? false;
  602. }
  603. else
  604. {
  605. foreach (var row in rows)
  606. if (column.Action?.Invoke(row) == true)
  607. bRefresh = true;
  608. }
  609. if (bRefresh)
  610. Dispatcher.BeginInvoke(() => { Refresh(true, true); });
  611. }
  612. void IDynamicGridUIComponentParent<T>.OpenColumnMenu(DynamicColumnBase column)
  613. {
  614. if(column is DynamicMenuColumn menuColumn)
  615. {
  616. menuColumn.Action?.Invoke(SelectedRows.FirstOrDefault());
  617. }
  618. else if(column is DynamicActionColumn actionColumn)
  619. {
  620. var menu = actionColumn?.ContextMenu?.Invoke(SelectedRows);
  621. if (menu != null && menu.Items.Count > 0)
  622. {
  623. menu.IsOpen = true;
  624. }
  625. }
  626. }
  627. void IDynamicGridUIComponentParent<T>.UpdateRecordCount(int count)
  628. {
  629. Count.Content = string.Format("{0} Records", count);
  630. }
  631. void IDynamicGridUIComponentParent<T>.LoadColumnsMenu(ContextMenu menu)
  632. {
  633. menu.AddItem("Select Columns", null, SelectColumnsClick);
  634. LoadColumnsMenu(menu);
  635. }
  636. void IDynamicGridUIComponentParent<T>.DragOver(object sender, DragEventArgs e)
  637. {
  638. HandleDragOver(sender, e);
  639. }
  640. void IDynamicGridUIComponentParent<T>.Drop(object sender, DragEventArgs e)
  641. {
  642. if (!HasOption(DynamicGridOption.DragTarget))
  643. return;
  644. if(DynamicGridUtils.TryGetDropData(e, out var entityType, out var table))
  645. {
  646. OnDragEnd(entityType, table, e);
  647. }
  648. else
  649. {
  650. HandleDragDrop(sender, e);
  651. }
  652. }
  653. void IDynamicGridUIComponentParent<T>.DragStart(object? sender, CoreRow[] rows)
  654. {
  655. Logger.Send(LogType.Information, "", "RowDragDropController_DragStart");
  656. if (!HasOption(DynamicGridOption.DragSource))
  657. return;
  658. OnRowsDragStart(rows);
  659. }
  660. #endregion
  661. protected virtual DynamicGridRowStyleSelector<T> GetRowStyleSelector()
  662. {
  663. return new DynamicGridRowStyleSelector<T, DynamicGridRowStyle>();
  664. }
  665. protected virtual DynamicGridStyle GetRowStyle(CoreRow row, DynamicGridStyle style)
  666. {
  667. DynamicGridStyle? result = null;
  668. if (ClipBuffer != null)
  669. if (ClipBuffer.Item2.Contains(row))
  670. {
  671. var bgbrush = style.Background as SolidColorBrush;
  672. var bgcolor = bgbrush != null ? bgbrush.Color : Colors.Transparent;
  673. result = new DynamicGridRowStyle(style);
  674. result.Background = ClipBuffer.Item1 == ClipAction.Cut
  675. ? new SolidColorBrush(bgcolor.MixColors(0.5, Colors.Orchid))
  676. : new SolidColorBrush(bgcolor.MixColors(0.5, Colors.LightGreen));
  677. result.Foreground = new SolidColorBrush(Colors.Gray);
  678. result.FontStyle = FontStyles.Italic;
  679. }
  680. result ??= OnGetRowStyle != null ? OnGetRowStyle(row, style) : style;
  681. return result;
  682. }
  683. protected virtual void BeforeSelection(CancelEventArgs cancel)
  684. {
  685. OnBeforeSelection?.Invoke(cancel);
  686. }
  687. public bool IsReady { get; protected set; }
  688. public UIElement? Header
  689. {
  690. get => _header;
  691. set
  692. {
  693. if (_header is not null && Layout.Children.Contains(_header))
  694. Layout.Children.Remove(_header);
  695. _header = value;
  696. if (_header is not null)
  697. {
  698. _header.SetValue(Grid.RowProperty, 0);
  699. _header.SetValue(Grid.ColumnProperty, 0);
  700. _header.SetValue(Grid.ColumnSpanProperty, 2);
  701. Layout.Children.Add(_header);
  702. }
  703. }
  704. }
  705. /// <summary>
  706. /// Represents the data in the grid. This is <see langword="null"/> until <see cref="Refresh(bool, bool)"/> is called.
  707. /// </summary>
  708. public CoreTable? MasterData { get; set; }
  709. public DynamicGridColumns MasterColumns { get; protected set; }
  710. public DynamicGridColumns VisibleColumns { get; protected set; }
  711. public DynamicActionColumns ActionColumns { get; protected set; }
  712. public CoreTable Data { get; set; }
  713. public class HiddenColumnsList
  714. {
  715. private List<string> Columns { get; set; } = new();
  716. public IEnumerable<string> ColumnNames => Columns;
  717. public void Add(Expression<Func<T, object?>> column) => Add(CoreUtils.GetFullPropertyName(column, "."));
  718. public void Add(IColumn column) => Add(column.Property);
  719. public void Add(string column)
  720. {
  721. if (!Contains(column))
  722. Columns.Add(column);
  723. }
  724. public bool Contains(string column) => Columns.Contains(column);
  725. }
  726. public void AddHiddenColumn(string column) => HiddenColumns.Add(column);
  727. public HiddenColumnsList HiddenColumns { get; }
  728. private static bool IsSequenced => typeof(T).GetInterfaces().Any(x => x.Equals(typeof(ISequenceable)));
  729. public double RowHeight
  730. {
  731. get => UIComponent.RowHeight;
  732. set => UIComponent.RowHeight = value;
  733. }
  734. public double HeaderHeight
  735. {
  736. get => UIComponent.HeaderRowHeight;
  737. set => UIComponent.HeaderRowHeight = value;
  738. }
  739. #region Options
  740. /// <summary>
  741. /// Initialise things like custom buttons; called once during construction.
  742. /// </summary>
  743. protected abstract void Init();
  744. protected abstract void DoReconfigure(FluentList<DynamicGridOption> options);
  745. private bool _hasLoadedOptions = false;
  746. protected virtual void OptionsChanged()
  747. {
  748. var reloadColumns = false;
  749. Help.Visibility = HasOption(DynamicGridOption.ShowHelp) ? Visibility.Visible : Visibility.Collapsed;
  750. Add.Visibility = HasOption(DynamicGridOption.AddRows) ? Visibility.Visible : Visibility.Collapsed;
  751. Edit.Visibility = HasOption(DynamicGridOption.EditRows) ? Visibility.Visible : Visibility.Collapsed;
  752. EditSpacer.Visibility = HasOption(DynamicGridOption.AddRows) || HasOption(DynamicGridOption.EditRows)
  753. ? Visibility.Visible
  754. : Visibility.Collapsed;
  755. Print.Visibility = HasOption(DynamicGridOption.Print) ? Visibility.Visible : Visibility.Collapsed;
  756. PrintSpacer.Visibility = HasOption(DynamicGridOption.Print) ? Visibility.Visible : Visibility.Collapsed;
  757. Cut.Visibility = IsSequenced && HasOption(DynamicGridOption.EditRows) ? Visibility.Visible : Visibility.Collapsed;
  758. Copy.Visibility = IsSequenced && HasOption(DynamicGridOption.EditRows) ? Visibility.Visible : Visibility.Collapsed;
  759. Paste.Visibility = IsSequenced && HasOption(DynamicGridOption.EditRows) ? Visibility.Visible : Visibility.Collapsed;
  760. ClipboardSpacer.Visibility = IsSequenced && HasOption(DynamicGridOption.EditRows) ? Visibility.Visible : Visibility.Collapsed;
  761. Export.Visibility = HasOption(DynamicGridOption.ExportData) ? Visibility.Visible : Visibility.Collapsed;
  762. Import.Visibility = HasOption(DynamicGridOption.ImportData) ? Visibility.Visible : Visibility.Collapsed;
  763. ExportSpacer.Visibility = HasOption(DynamicGridOption.ExportData) || HasOption(DynamicGridOption.ImportData)
  764. ? Visibility.Visible
  765. : Visibility.Collapsed;
  766. SwitchViewBtn.Visibility = HasOption(DynamicGridOption.DirectEdit) ? Visibility.Visible : Visibility.Collapsed;
  767. Count.Visibility = HasOption(DynamicGridOption.RecordCount) ? Visibility.Visible : Visibility.Collapsed;
  768. Delete.Visibility = HasOption(DynamicGridOption.DeleteRows) ? Visibility.Visible : Visibility.Collapsed;
  769. if (up != null)
  770. up.Position = HasOption(DynamicGridOption.EditRows) ? DynamicActionColumnPosition.Start : DynamicActionColumnPosition.Hidden;
  771. if (down != null)
  772. down.Position = HasOption(DynamicGridOption.EditRows) ? DynamicActionColumnPosition.Start : DynamicActionColumnPosition.Hidden;
  773. if (DuplicateBtn != null)
  774. DuplicateBtn.Visibility = Visibility.Collapsed;
  775. reloadColumns = reloadColumns || UIComponent.OptionsChanged();
  776. if(reloadColumns)
  777. {
  778. Refresh(true, false);
  779. }
  780. }
  781. public bool IsDirectEditMode(IEnumerable<DynamicGridOption>? options = null)
  782. {
  783. return HasOption(DynamicGridOption.DirectEdit, options)
  784. && (Settings.ViewMode == DynamicGridSettings.DynamicGridViewMode.DirectEdit
  785. || Settings.ViewMode == DynamicGridSettings.DynamicGridViewMode.Default);
  786. }
  787. private void SwitchView_Click(object sender, RoutedEventArgs e)
  788. {
  789. Settings.ViewMode = Settings.ViewMode switch
  790. {
  791. DynamicGridSettings.DynamicGridViewMode.Default => DynamicGridSettings.DynamicGridViewMode.Normal,
  792. DynamicGridSettings.DynamicGridViewMode.Normal => DynamicGridSettings.DynamicGridViewMode.DirectEdit,
  793. DynamicGridSettings.DynamicGridViewMode.DirectEdit or _ => DynamicGridSettings.DynamicGridViewMode.Normal
  794. };
  795. SaveSettings(Settings);
  796. Reconfigure();
  797. }
  798. public FluentList<DynamicGridOption> Options { get; }
  799. protected void OnReconfigureEvent(FluentList<DynamicGridOption> options)
  800. {
  801. OnReconfigure?.Invoke(options);
  802. }
  803. /// <summary>
  804. /// Configure custom buttons and options.
  805. /// </summary>
  806. public void Reconfigure(FluentList<DynamicGridOption> options)
  807. {
  808. options.BeginUpdate().Clear();
  809. DoReconfigure(options);
  810. OnReconfigureEvent(options);
  811. options.EndUpdate();
  812. if (!_hasLoadedOptions)
  813. {
  814. _hasLoadedOptions = true;
  815. OptionsChanged();
  816. }
  817. }
  818. public void Reconfigure()
  819. {
  820. Reconfigure(Options);
  821. }
  822. public void Reconfigure(ReconfigureEvent onReconfigure)
  823. {
  824. OnReconfigure += onReconfigure;
  825. Reconfigure();
  826. }
  827. public bool HasOption(DynamicGridOption option, IEnumerable<DynamicGridOption>? options = null) => (options ?? Options).Contains(option);
  828. bool IDynamicGrid.HasOption(InABox.DynamicGrid.DynamicGridOption option) => HasOption(option, null);
  829. #endregion
  830. protected virtual DynamicGridSettings LoadSettings()
  831. {
  832. return new DynamicGridSettings();
  833. }
  834. protected virtual void SaveSettings(DynamicGridSettings settings)
  835. {
  836. }
  837. protected virtual void LoadColumnsMenu(ContextMenu menu)
  838. {
  839. }
  840. protected void UpdateCell(int row, string colname, object? value)
  841. {
  842. var coreRow = Data.Rows[row];
  843. coreRow[colname] = value;
  844. UIComponent.UpdateCell(coreRow, colname, value);
  845. }
  846. private void EntityChanged(T obj, CoreRow row, string changedColumn, Dictionary<string, object?> changes)
  847. {
  848. OnAfterEditorValueChanged(null, new T[] { obj }, new AfterEditorValueChangedArgs(changedColumn, changes), changes);
  849. SaveItem(obj);
  850. foreach (var (key, value) in changes)
  851. {
  852. row[key] = value;
  853. }
  854. UIComponent.UpdateRow(row);
  855. }
  856. #region Row Selections
  857. protected CoreRow[] GetVisibleRows()
  858. {
  859. return UIComponent.GetVisibleRows();
  860. }
  861. public CoreRow[] SelectedRows
  862. {
  863. get => UIComponent.SelectedRows;
  864. set => UIComponent.SelectedRows = value;
  865. }
  866. /// <summary>
  867. /// Call the <see cref="OnSelectItem"/> event, and do any updating which needs to occur when items are selected.
  868. /// </summary>
  869. /// <param name="rows"></param>
  870. protected virtual void SelectItems(CoreRow[]? rows)
  871. {
  872. if (IsReady)
  873. OnSelectItem?.Invoke(this, new DynamicGridSelectionEventArgs(rows));
  874. DuplicateBtn.Visibility =
  875. typeof(T).IsAssignableTo(typeof(IDuplicatable)) && rows != null && rows.Length >= 1 ? Visibility.Visible : Visibility.Collapsed;
  876. }
  877. protected virtual void DoDoubleClick(object sender)
  878. {
  879. if (IsDirectEditMode())
  880. return;
  881. //SelectItems(SelectedRows);
  882. var args = new HandledEventArgs(false);
  883. OnDoubleClick?.Invoke(sender, args);
  884. if (args.Handled)
  885. return;
  886. if (HasOption(DynamicGridOption.EditRows))
  887. DoEdit();
  888. }
  889. #endregion
  890. #region Column Handling
  891. protected virtual DynamicGridColumns LoadColumns()
  892. {
  893. var result = new DynamicGridColumns();
  894. var cols = IsDirectEditMode()
  895. ? new Columns<T>().Default(ColumnType.IncludeForeignKeys, ColumnType.ExcludeID)
  896. : new Columns<T>().Default(ColumnType.IncludeLinked, ColumnType.ExcludeID);
  897. result.AddRange(MasterColumns.Where(x => cols.Items.Any(c => c.Property.Equals(x.ColumnName)))
  898. .OrderBy(x => CoreUtils.GetPropertySequence(typeof(T), x.ColumnName)));
  899. return result;
  900. }
  901. /// <summary>
  902. /// Provide a set of columns which is the default for this grid.
  903. /// </summary>
  904. public virtual DynamicGridColumns GenerateColumns()
  905. {
  906. var columns = new DynamicGridColumns();
  907. var cols = IsDirectEditMode()
  908. ? new Columns<T>().Default(ColumnType.IncludeForeignKeys, ColumnType.ExcludeID)
  909. : new Columns<T>().Default(ColumnType.IncludeLinked, ColumnType.ExcludeID);
  910. if (cols != null)
  911. {
  912. foreach (var col in cols.Items)
  913. {
  914. var mc = MasterColumns.FirstOrDefault(x => x.ColumnName.Equals(col.Property));
  915. if (mc != null && mc.Editor is not NullEditor && mc.Editor.Visible != Visible.Hidden)
  916. columns.Add(mc);
  917. }
  918. }
  919. return columns;
  920. }
  921. private bool SwapRows(int row1, int row2)
  922. {
  923. CoreRow[] rows = Data.Rows.Where(x => x.Index.Equals(row1) || x.Index.Equals(row2)).ToArray();
  924. var items = LoadItems(rows);
  925. var first = (items.First() as ISequenceable)!;
  926. var last = (items.Last() as ISequenceable)!;
  927. var iBuf1 = first.Sequence;
  928. var iBuf2 = last.Sequence;
  929. first.Sequence = iBuf2;
  930. last.Sequence = iBuf1;
  931. SaveItems(items);
  932. return true;
  933. }
  934. protected virtual void SaveColumns(DynamicGridColumns columns)
  935. {
  936. }
  937. public int DesiredWidth()
  938. {
  939. return UIComponent.DesiredWidth();
  940. }
  941. public virtual void ConfigureColumns(DynamicGridColumns columns)
  942. {
  943. DoCustomiseColumnsEvent(this,columns);
  944. }
  945. private void ReloadColumns()
  946. {
  947. ConfigureColumns(MasterColumns /*, false */);
  948. VisibleColumns = LoadColumns();
  949. ConfigureColumns(VisibleColumns /*, true */);
  950. UIComponent.RefreshColumns(VisibleColumns, ActionColumns);
  951. }
  952. #endregion
  953. #region Refresh / Reload
  954. protected abstract void Reload(Filters<T> criteria, Columns<T> columns, ref SortOrder<T>? sort, Action<CoreTable?, Exception?> action);
  955. public Filter<T>? DefineFilter()
  956. {
  957. if (OnDefineFilter is null)
  958. return null;
  959. var result = OnDefineFilter.Invoke(typeof(T)) as Filter<T>;
  960. return result;
  961. }
  962. protected virtual bool FilterRecord(CoreRow row)
  963. {
  964. var bOK = ActionColumns.All(x =>
  965. {
  966. return x.FilterRecord is null || x.SelectedFilters is null || !x.SelectedFilters.Any()
  967. || x.FilterRecord.Invoke(row, x.SelectedFilters);
  968. });
  969. if (bOK && OnFilterRecord is not null)
  970. bOK = OnFilterRecord(row);
  971. return bOK;
  972. }
  973. public IEnumerable<TType> ExtractValues<TType>(Expression<Func<T, TType>> column, Selection selection)
  974. {
  975. var result = selection == Selection.None
  976. ? Enumerable.Empty<TType>()
  977. : selection == Selection.Selected
  978. ? SelectedRows.Select(r => r.Get(column))
  979. : Data.ExtractValues(column);
  980. return result;
  981. }
  982. public virtual void Refresh(bool reloadcolumns, bool reloaddata)
  983. {
  984. if (bRefreshing)
  985. return;
  986. if (!DoBeforeRefresh())
  987. return;
  988. UIComponent.BeforeRefresh();
  989. var cursor = UseWaitCursor ? new WaitCursor() : null;
  990. Loading.Visibility = Visibility.Visible;
  991. Loading.BeginAnimation(Label.OpacityProperty, LoadingFader);
  992. bRefreshing = true;
  993. if (reloadcolumns)
  994. ReloadColumns();
  995. if (reloaddata)
  996. {
  997. _lookupcache.Clear();
  998. var criteria = new Filters<T>();
  999. var filter = DefineFilter();
  1000. if (filter != null)
  1001. criteria.Add(filter);
  1002. var columns = DataColumns();
  1003. var sort = LookupFactory.DefineSort<T>();
  1004. if (sort == null && IsSequenced)
  1005. sort = new SortOrder<T>("Sequence");
  1006. Reload(
  1007. criteria
  1008. , columns
  1009. , ref sort
  1010. , (table, exception) =>
  1011. {
  1012. if (exception != null)
  1013. {
  1014. Dispatcher.Invoke(() =>
  1015. {
  1016. MessageWindow.ShowError("Sorry! We couldn't load the data.", exception);
  1017. });
  1018. }
  1019. else if (table is not null)
  1020. {
  1021. MasterData = table;
  1022. Dispatcher.Invoke(() =>
  1023. {
  1024. ProcessData();
  1025. DoAfterRefresh();
  1026. bRefreshing = false;
  1027. IsReady = true;
  1028. });
  1029. }
  1030. }
  1031. );
  1032. }
  1033. else
  1034. {
  1035. ProcessData();
  1036. DoAfterRefresh();
  1037. bRefreshing = false;
  1038. IsReady = true;
  1039. Loading.BeginAnimation(Label.OpacityProperty, null);
  1040. Loading.Visibility = Visibility.Collapsed;
  1041. }
  1042. if (cursor != null)
  1043. {
  1044. cursor.Dispose();
  1045. cursor = null;
  1046. }
  1047. }
  1048. protected void NotifyBeforeRefresh(BeforeRefreshEventArgs args) => BeforeRefresh?.Invoke(this, args);
  1049. protected void NotifyAfterRefresh(AfterRefreshEventArgs args) => AfterRefresh?.Invoke(this, args);
  1050. protected bool OnBeforeRefresh()
  1051. {
  1052. return true;
  1053. }
  1054. private bool DoBeforeRefresh()
  1055. {
  1056. var result = OnBeforeRefresh();
  1057. if (result)
  1058. {
  1059. var args = new BeforeRefreshEventArgs() { Cancel = false };
  1060. NotifyBeforeRefresh(args);
  1061. result = args.Cancel == false;
  1062. }
  1063. return result;
  1064. }
  1065. protected virtual void OnAfterRefresh()
  1066. {
  1067. }
  1068. protected void DoAfterRefresh()
  1069. {
  1070. OnAfterRefresh();
  1071. NotifyAfterRefresh(new AfterRefreshEventArgs());
  1072. }
  1073. public Columns<T> DataColumns()
  1074. {
  1075. var columns = new Columns<T>();
  1076. foreach (var column in VisibleColumns)
  1077. columns.Add(column.ColumnName);
  1078. foreach (var column in HiddenColumns.ColumnNames)
  1079. columns.Add(new Column<T>(column));
  1080. return columns;
  1081. }
  1082. private void ProcessData()
  1083. {
  1084. Data.Columns.Clear();
  1085. Data.Setters.Clear();
  1086. if (MasterData != null)
  1087. foreach (var column in MasterData.Columns)
  1088. Data.Columns.Add(column);
  1089. LoadData();
  1090. }
  1091. protected readonly Dictionary<CoreRow, CoreRow> _recordmap = new();
  1092. public void UpdateRow<TRow, TType>(CoreRow row, Expression<Func<TRow, TType>> column, TType value, bool refresh = true)
  1093. {
  1094. row.Set(column, value);
  1095. _recordmap[row].Set(column, value);
  1096. if (refresh)
  1097. InvalidateRow(row);
  1098. }
  1099. public void UpdateRow<TType>(CoreRow row, string column, TType value, bool refresh = true)
  1100. {
  1101. row.Set(column, value);
  1102. _recordmap[row].Set(column, value);
  1103. if (refresh)
  1104. InvalidateRow(row);
  1105. }
  1106. public void AddRow(CoreRow row)
  1107. {
  1108. if (MasterData is null) return;
  1109. var masterrow = MasterData.NewRow();
  1110. MasterData.LoadRow(masterrow, row);
  1111. Refresh(false, false);
  1112. }
  1113. public void AddRow(T data)
  1114. {
  1115. if (MasterData is null) return;
  1116. var masterrow = MasterData.NewRow();
  1117. MasterData.LoadRow(masterrow, data);
  1118. MasterData.Rows.Add(masterrow);
  1119. Refresh(false, false);
  1120. }
  1121. public void DeleteRow(CoreRow row)
  1122. {
  1123. if (MasterData is null) return;
  1124. var masterrow = _recordmap[row];
  1125. MasterData.Rows.Remove(masterrow);
  1126. Refresh(false, false);
  1127. }
  1128. private void FilterRows(CoreTable from, CoreTable into, Dictionary<CoreRow, CoreRow>? recordMap = null, Func<CoreRow, bool>? filter = null)
  1129. {
  1130. into.Rows.Clear();
  1131. recordMap?.Clear();
  1132. foreach (var row in from.Rows.ToArray())
  1133. if (FilterRecord(row) && filter?.Invoke(row) != false)
  1134. {
  1135. var newrow = into.NewRow();
  1136. for (var i = 0; i < into.Columns.Count; i++)
  1137. {
  1138. var value = i < row.Values.Count ? row.Values[i] : null;
  1139. if (into.Columns[i].DataType.IsNumeric())
  1140. value = into.Columns[i].DataType.IsDefault(value) ? null : value;
  1141. //else if (Data.Columns[i].DataType == typeof(String[]))
  1142. // value = String.Join("\n", value as String[]);
  1143. newrow.Values.Add(value);
  1144. }
  1145. //newrow.Values.AddRange(row.Values);
  1146. //if ((OnFilterRecord == null) || (OnFilterRecord(row)))
  1147. into.Rows.Add(newrow);
  1148. recordMap?.TryAdd(newrow, row);
  1149. }
  1150. }
  1151. private void LoadData()
  1152. {
  1153. ResetClipBuffer();
  1154. if (MasterData is null)
  1155. return;
  1156. FilterRows(MasterData, Data, _recordmap);
  1157. InvalidateGrid();
  1158. //ScrollBar.Value = _CurrentRow <= 0 ? 0 : _CurrentRow;
  1159. SelectedRows = Array.Empty<CoreRow>();
  1160. }
  1161. //IncrementalList<T> _data = null;
  1162. public void InvalidateRow(CoreRow row)
  1163. {
  1164. UIComponent.InvalidateRow(row);
  1165. }
  1166. private void InvalidateGrid()
  1167. {
  1168. if (RowStyleSelector != null)
  1169. RowStyleSelector.Data = Data;
  1170. UIComponent.RefreshData(Data);
  1171. Loading.BeginAnimation(Label.OpacityProperty, null);
  1172. Loading.Visibility = Visibility.Collapsed;
  1173. }
  1174. public void AddVisualFilter(string column, string value, FilterType filtertype = FilterType.Contains)
  1175. {
  1176. UIComponent.AddVisualFilter(column, value, filtertype);
  1177. }
  1178. #endregion
  1179. #region Item Manipulation
  1180. #region Load/Save/Delete
  1181. public virtual T[] LoadItems(CoreRow[] rows)
  1182. {
  1183. var result = new List<T>();
  1184. foreach (var row in rows)
  1185. {
  1186. var index = Data.Rows.IndexOf(row);
  1187. result.Add(LoadItem(row));
  1188. }
  1189. return result.ToArray();
  1190. }
  1191. public abstract T LoadItem(CoreRow row);
  1192. public abstract void SaveItem(T item);
  1193. public virtual void SaveItems(T[] items)
  1194. {
  1195. foreach (var item in items)
  1196. SaveItem(item);
  1197. }
  1198. protected virtual bool CanDeleteItems(params CoreRow[] rows)
  1199. {
  1200. return true;
  1201. }
  1202. public abstract void DeleteItems(params CoreRow[] rows);
  1203. protected virtual void DoDelete()
  1204. {
  1205. var rows = SelectedRows.ToArray();
  1206. if (rows.Any())
  1207. if (CanDeleteItems(rows))
  1208. if (MessageBox.Show("Are you sure you wish to delete the selected records?", "Confirm Delete", MessageBoxButton.YesNo) ==
  1209. MessageBoxResult.Yes)
  1210. {
  1211. DeleteItems(rows);
  1212. SelectedRows = Array.Empty<CoreRow>();
  1213. OnChanged?.Invoke(this, EventArgs.Empty);
  1214. Refresh(false, true);
  1215. SelectItems(null);
  1216. }
  1217. }
  1218. private void Delete_Click(object sender, RoutedEventArgs e)
  1219. {
  1220. DoDelete();
  1221. }
  1222. #endregion
  1223. #region Edit
  1224. protected virtual void DoEdit()
  1225. {
  1226. if (!SelectedRows.Any())
  1227. return;
  1228. if (AddEditClick(SelectedRows))
  1229. {
  1230. SelectItems(SelectedRows);
  1231. }
  1232. }
  1233. private void Edit_Click(object sender, RoutedEventArgs e)
  1234. {
  1235. DoEdit();
  1236. }
  1237. protected virtual void DoAdd(bool OpenEditorOnDirectEdit = false)
  1238. {
  1239. //CoreRow row = (SelectedRow > -1) && (SelectedRow < Data.Rows.Count) ? Data.Rows[this.SelectedRow] : null;
  1240. if (IsDirectEditMode() && !OpenEditorOnDirectEdit)
  1241. {
  1242. var item = CreateItem();
  1243. SaveItem(item);
  1244. var datarow = Data.NewRow();
  1245. ObjectToRow(item, datarow);
  1246. Data.Rows.Add(datarow);
  1247. var masterrow = MasterData.NewRow();
  1248. ObjectToRow(item, masterrow);
  1249. MasterData.Rows.Add(masterrow);
  1250. _recordmap[datarow] = masterrow;
  1251. InvalidateGrid();
  1252. SelectedRows = new[] { datarow };
  1253. OnChanged?.Invoke(this, EventArgs.Empty);
  1254. }
  1255. else if (AddEditClick(null))
  1256. {
  1257. Refresh(false, true);
  1258. }
  1259. }
  1260. private void Add_Click(object sender, RoutedEventArgs e)
  1261. {
  1262. if (CanCreateItems())
  1263. DoAdd();
  1264. }
  1265. public virtual DynamicEditorPages LoadEditorPages(T item)
  1266. {
  1267. DynamicEditorPages pages = new DynamicEditorPages();
  1268. DynamicGridUtils.LoadOneToManyPages(typeof(T), pages);
  1269. DynamicGridUtils.LoadEnclosedListPages(typeof(T), pages);
  1270. DynamicGridUtils.LoadManyToManyPages(typeof(T), pages);
  1271. DynamicGridUtils.LoadCustomEditorPages(typeof(T), pages);
  1272. foreach (var page in pages)
  1273. page.Ready = false;
  1274. return pages;
  1275. }
  1276. public virtual void LoadEditorButtons(T item, DynamicEditorButtons buttons)
  1277. {
  1278. buttons.Clear();
  1279. buttons.Add(
  1280. "",
  1281. Wpf.Resources.help.AsBitmapImage(),
  1282. item,
  1283. (f, i) =>
  1284. {
  1285. Process.Start(new ProcessStartInfo("https://prsdigital.com.au/wiki/index.php/" + typeof(T).Name.SplitCamelCase().Replace(" ", "_"))
  1286. { UseShellExecute = true });
  1287. }
  1288. );
  1289. OnLoadEditorButtons?.Invoke(item, buttons);
  1290. }
  1291. protected virtual void BeforeLoad(IDynamicEditorForm form, T[] items)
  1292. {
  1293. form.BeforeLoad();
  1294. }
  1295. void IDynamicGrid.InitialiseEditorForm(IDynamicEditorForm editor, object[] items, Func<Type, CoreTable>? pageDataHandler, bool preloadPages)
  1296. {
  1297. InitialiseEditorForm(editor, items.Cast<T>().ToArray(), pageDataHandler, preloadPages);
  1298. }
  1299. public virtual bool EditItems(object[] items, Func<Type, CoreTable?>? PageDataHandler = null, bool PreloadPages = false)
  1300. {
  1301. var values = items.Cast<T>().ToArray();
  1302. return EditItems(values, PageDataHandler, PreloadPages);
  1303. }
  1304. public virtual void InitialiseEditorForm(IDynamicEditorForm editor, T[] items, Func<Type, CoreTable?>? pageDataHandler = null, bool preloadPages = false)
  1305. {
  1306. var pages = items.Length == 1 ? LoadEditorPages(items.First()) : new DynamicEditorPages();
  1307. var buttons = new DynamicEditorButtons();
  1308. if (items.Length == 1)
  1309. LoadEditorButtons(items.First(), buttons);
  1310. editor.Setup(items.Any() ? items.First().GetType() : typeof(T), pages, buttons, pageDataHandler, preloadPages);
  1311. editor.OnCustomiseColumns = (sender, columns) =>
  1312. {
  1313. columns.Clear();
  1314. columns.AddRange(MasterColumns);
  1315. ConfigureColumns(columns);
  1316. };
  1317. editor.OnDefineEditor = (o, c) =>
  1318. {
  1319. var result = GetEditor(o, c);
  1320. if (result != null)
  1321. result = result.CloneEditor();
  1322. return result;
  1323. };
  1324. editor.OnFormCustomiseEditor += DoCustomiseEditor;
  1325. editor.OnDefineFilter = (type, column) => { return DefineLookupFilter(type, column, items); };
  1326. //editor.OnDefineFilter += (o, e) => { return DefineFilter(items, e); };
  1327. editor.OnDefineLookups = editor => DefineLookups(editor, items);
  1328. editor.OnEditorValueChanged += (s, n, v) => EditorValueChanged(editor, items, n, v);
  1329. editor.OnAfterEditorValueChanged += (g, args) => AfterEditorValueChanged(g, items, args);
  1330. editor.OnReconfigureEditors = g => DoReconfigureEditors(g, items);
  1331. editor.OnValidateData += (o, i) => ValidateData(items);
  1332. editor.OnSelectPage += SelectPage;
  1333. editor.OnSaveItem = (o, e) =>
  1334. {
  1335. try
  1336. {
  1337. using var Wait = new WaitCursor();
  1338. DoBeforeSave(editor, items);
  1339. if (items.Length == 1)
  1340. editor.UnloadEditorPages(false);
  1341. foreach (var item in items)
  1342. SaveItem(item);
  1343. if (items.Length == 1)
  1344. editor.UnloadEditorPages(true);
  1345. DoAfterSave(editor, items);
  1346. }
  1347. catch (Exception err)
  1348. {
  1349. MessageBox.Show(err.Message);
  1350. e.Cancel = true;
  1351. }
  1352. };
  1353. BeforeLoad(editor, items);
  1354. editor.Items = items;
  1355. AfterLoad(editor, items);
  1356. }
  1357. private void DoCustomiseEditor(IDynamicEditorForm sender, object[] items, DynamicGridColumn column, BaseEditor editor)
  1358. {
  1359. CustomiseEditor((T[])items, column, editor);
  1360. OnCustomiseEditor?.Invoke(sender, (T[])items, column, editor);
  1361. }
  1362. protected virtual void CustomiseEditor(T[] items, DynamicGridColumn column, BaseEditor editor)
  1363. {
  1364. }
  1365. protected virtual void DoAfterSave(IDynamicEditorForm editor, T[] items)
  1366. {
  1367. OnAfterSave?.Invoke(editor, items);
  1368. }
  1369. protected virtual void DoBeforeSave(IDynamicEditorForm editor, T[] items)
  1370. {
  1371. OnBeforeSave?.Invoke(editor, items);
  1372. }
  1373. public virtual bool EditItems(T[] items, Func<Type, CoreTable?>? PageDataHandler = null, bool PreloadPages = false)
  1374. {
  1375. DynamicEditorForm editor;
  1376. using (var cursor = new WaitCursor())
  1377. {
  1378. editor = new DynamicEditorForm();
  1379. editor.SetValue(Panel.ZIndexProperty, 999);
  1380. InitialiseEditorForm(editor, items, PageDataHandler, PreloadPages);
  1381. OnEditorLoaded?.Invoke(editor, items);
  1382. }
  1383. return editor.ShowDialog() == true;
  1384. }
  1385. private Dictionary<String, object?> AfterEditorValueChanged(DynamicEditorGrid grid, T[] items, AfterEditorValueChangedArgs args)
  1386. {
  1387. var changes = new Dictionary<string, object?>();
  1388. OnAfterEditorValueChanged(grid, items, args, changes);
  1389. return changes;
  1390. }
  1391. protected virtual void OnAfterEditorValueChanged(DynamicEditorGrid? grid, T[] items, AfterEditorValueChangedArgs args, Dictionary<String, object?> changes)
  1392. {
  1393. }
  1394. protected virtual void DoReconfigureEditors(DynamicEditorGrid grid, T[] items)
  1395. {
  1396. /*if (items.First() is IDimensioned dimensioned)
  1397. {
  1398. UpdateEditor(grid, x => x.Dimensions.Quantity, dimensioned.Dimensions.GetUnit().HasQuantity);
  1399. UpdateEditor(grid, x => x.Dimensions.Length, dimensioned.Dimensions.GetUnit().HasLength);
  1400. UpdateEditor(grid, x => x.Dimensions.Width, dimensioned.Dimensions.GetUnit().HasWidth);
  1401. UpdateEditor(grid, x => x.Dimensions.Height, dimensioned.Dimensions.GetUnit().HasHeight);
  1402. UpdateEditor(grid, x => x.Dimensions.Weight, dimensioned.Dimensions.GetUnit().HasWeight);
  1403. }*/
  1404. }
  1405. private string[]? ValidateData(T[] items)
  1406. {
  1407. var errors = new List<string>();
  1408. DoValidate(items, errors);
  1409. OnValidate?.Invoke(this, items, errors);
  1410. return errors.Any() ? errors.ToArray() : null;
  1411. }
  1412. protected virtual void DoValidate(T[] items, List<string> errors)
  1413. {
  1414. }
  1415. protected virtual void AfterLoad(IDynamicEditorForm editor, T[] items)
  1416. {
  1417. editor.AfterLoad();
  1418. }
  1419. protected virtual void SelectPage(object sender, BaseObject[]? items)
  1420. {
  1421. }
  1422. protected virtual Dictionary<string, object?> EditorValueChanged(IDynamicEditorForm editor, T[] items, string name, object value)
  1423. {
  1424. var result = DynamicGridUtils.UpdateEditorValue(items, name, value);
  1425. if (OnEditorValueChanged != null)
  1426. {
  1427. var newchanges = OnEditorValueChanged(editor, name, value);
  1428. foreach (var key in newchanges.Keys)
  1429. result[key] = newchanges[key];
  1430. }
  1431. return result;
  1432. }
  1433. private readonly Dictionary<Tuple<Type, Type>, Dictionary<object, object>> _lookupcache = new();
  1434. protected virtual void DefineLookups(ILookupEditorControl sender, T[] items, bool async = true)
  1435. {
  1436. if (sender.EditorDefinition is not ILookupEditor editor)
  1437. return;
  1438. var colname = sender.ColumnName;
  1439. if (async)
  1440. {
  1441. Task.Run(() =>
  1442. {
  1443. try
  1444. {
  1445. var values = editor.Values(typeof(T), colname, items);
  1446. Dispatcher.Invoke(
  1447. () =>
  1448. {
  1449. try
  1450. {
  1451. //Logger.Send(LogType.Information, typeof(T).Name, "Dispatching Results" + colname);
  1452. sender.LoadLookups(values);
  1453. }
  1454. catch (Exception e2)
  1455. {
  1456. Logger.Send(LogType.Information, typeof(T).Name,
  1457. "Exception (2) in LoadLookups: " + e2.Message + "\n" + e2.StackTrace);
  1458. }
  1459. }
  1460. );
  1461. }
  1462. catch (Exception e)
  1463. {
  1464. Logger.Send(LogType.Information, typeof(T).Name,
  1465. "Exception (1) in LoadLookups: " + e.Message + "\n" + e.StackTrace);
  1466. }
  1467. });
  1468. }
  1469. else
  1470. {
  1471. var values = editor.Values(typeof(T), colname, items);
  1472. sender.LoadLookups(values);
  1473. }
  1474. }
  1475. /// <summary>
  1476. /// Retrieves an editor to display for the given column of <paramref name="item"/>.
  1477. /// </summary>
  1478. /// <param name="item">The object being edited.</param>
  1479. /// <param name="column">The column of the editor.</param>
  1480. /// <returns>A new editor, or <see langword="null"/> if no editor defined and no sensible default exists.</returns>
  1481. protected virtual BaseEditor? GetEditor(object item, DynamicGridColumn column)
  1482. {
  1483. return column.Editor ?? CoreUtils.GetProperty(item.GetType(), column.ColumnName).GetEditor();
  1484. }
  1485. protected IFilter? DefineLookupFilter(Type type, string column, T[] items)
  1486. {
  1487. return LookupFactory.DefineLookupFilter(typeof(T), type, column, items);
  1488. }
  1489. protected virtual void SetEditorValue(object item, string name, object value)
  1490. {
  1491. try
  1492. {
  1493. CoreUtils.SetPropertyValue(item, name, value);
  1494. }
  1495. catch (Exception e)
  1496. {
  1497. Logger.Send(LogType.Error, "", string.Format("*** Unknown Error: {0}\n{1}", e.Message, e.StackTrace));
  1498. }
  1499. }
  1500. protected virtual object? GetEditorValue(object item, string name)
  1501. {
  1502. return CoreUtils.GetPropertyValue(item, name);
  1503. }
  1504. protected virtual bool CanCreateItems()
  1505. {
  1506. return true;
  1507. }
  1508. private bool AddEditClick(CoreRow[]? rows)
  1509. {
  1510. if (!IsEnabled || bRefreshing)
  1511. return false;
  1512. if (rows == null || !rows.Any())
  1513. {
  1514. if (!CanCreateItems())
  1515. return false;
  1516. var item = CreateItem();
  1517. // Yea, and this won't work, because we're actually usually showing the description of a linked item,
  1518. // not the id of the link, and we need to set the ID to have it work properly :-(
  1519. //foreach (String key in VisualFilters.Keys)
  1520. // CoreUtils.SetPropertyValue(item, key, VisualFilters[key]);
  1521. if (EditItems(new[] { item }))
  1522. {
  1523. //_CurrentRow = Data.Rows.Count;
  1524. var row = Data.NewRow();
  1525. ObjectToRow(item, row);
  1526. Data.Rows.Add(row);
  1527. InvalidateGrid();
  1528. SelectedRows = new[] { row };
  1529. DoChanged();
  1530. return true;
  1531. }
  1532. return false;
  1533. }
  1534. var items = Array.Empty<T>();
  1535. using (new WaitCursor())
  1536. {
  1537. Stopwatch sw = new Stopwatch();
  1538. sw.Start();
  1539. items = LoadItems(rows);
  1540. //Logger.Send(LogType.Information, "DG:LoadItems", String.Format("Loaded Items: {0}ms", sw.ElapsedMilliseconds));
  1541. sw.Stop();
  1542. }
  1543. if (items.Any())
  1544. {
  1545. var sel = SelectedRows;
  1546. if (EditItems(items))
  1547. {
  1548. for (var i = 0; i < items.Length; i++)
  1549. {
  1550. ObjectToRow(items[i], rows[i]);
  1551. ObjectToRow(items[i], _recordmap[rows[i]]);
  1552. }
  1553. InvalidateGrid();
  1554. SelectedRows = sel;
  1555. DoChanged();
  1556. return true;
  1557. }
  1558. return false;
  1559. }
  1560. return false;
  1561. }
  1562. #endregion
  1563. #region Duplicate
  1564. protected virtual IEnumerable<T> LoadDuplicatorItems(CoreRow[] rows)
  1565. {
  1566. return LoadItems(rows);
  1567. }
  1568. private bool DoDuplicate(Button button, CoreRow[] rows)
  1569. {
  1570. if (!rows.Any())
  1571. {
  1572. MessageBox.Show("Please select at least one record to duplicate!");
  1573. return false;
  1574. }
  1575. /*var ids = ExtractValues(x => x.ID, Selection.Selected).ToArray();
  1576. if (!ids.Any())
  1577. {
  1578. MessageBox.Show("Please select at least one record to duplicate!");
  1579. return false;
  1580. }*/
  1581. var duplicator = (new T() as IDuplicatable)?.GetDuplicator();
  1582. if (duplicator is null)
  1583. {
  1584. MessageBox.Show($"Cannot duplicate {typeof(T)}");
  1585. return false;
  1586. }
  1587. duplicator.Duplicate(LoadDuplicatorItems(rows));// new Filter<T>(x => x.ID).InList(ids));
  1588. return true;
  1589. }
  1590. #endregion
  1591. public virtual T CreateItem()
  1592. {
  1593. var result = new T();
  1594. OnCreateItem?.Invoke(this, result);
  1595. return result;
  1596. }
  1597. protected virtual void DoPrint(object sender)
  1598. {
  1599. OnPrintData?.Invoke(sender);
  1600. }
  1601. protected virtual void ShowHelp(string slug)
  1602. {
  1603. Process.Start(new ProcessStartInfo("https://prsdigital.com.au/wiki/index.php/" + slug) { UseShellExecute = true });
  1604. }
  1605. protected void ReloadForms<TTargetType, TTargetForm, TSourceForm>(IDynamicEditorForm editor, TTargetType item,
  1606. Expression<Func<TSourceForm, object?>> sourcekey, Guid sourceid)
  1607. where TTargetType : Entity, new()
  1608. where TTargetForm : Entity, IRemotable, IPersistent, IDigitalFormInstance, new()
  1609. where TSourceForm : Entity, IRemotable, IPersistent, IDigitalForm<TTargetType>, new()
  1610. {
  1611. var type = typeof(IDynamicOneToManyGrid<,>).MakeGenericType(typeof(TTargetType), typeof(TTargetForm));
  1612. var page =
  1613. editor.Pages?.FirstOrDefault(x => x.GetType().GetInterfaces().Contains(type)) as IDynamicOneToManyGrid<TTargetType, TTargetForm>;
  1614. if (page != null && item != null)
  1615. {
  1616. if (!page.Ready)
  1617. page.Load(item, null);
  1618. CoreTable table;
  1619. if (sourceid == Guid.Empty)
  1620. {
  1621. table = new CoreTable();
  1622. table.LoadColumns(typeof(TSourceForm));
  1623. }
  1624. else
  1625. {
  1626. table = new Client<TSourceForm>().Query(
  1627. new Filter<TSourceForm>(sourcekey).IsEqualTo(sourceid).And(x => x.Form.AppliesTo)
  1628. .IsEqualTo(typeof(TTargetType).EntityName().Split('.').Last())
  1629. );
  1630. }
  1631. var newforms = new List<TTargetForm>();
  1632. foreach (var row in table.Rows)
  1633. {
  1634. var sourceform = row.ToObject<TSourceForm>();
  1635. var targetform = new TTargetForm();
  1636. targetform.Form.ID = sourceform.Form.ID;
  1637. targetform.Form.Synchronise(sourceform.Form);
  1638. newforms.Add(targetform);
  1639. }
  1640. page.Items.Clear();
  1641. page.LoadItems(newforms.ToArray());
  1642. }
  1643. }
  1644. #region ClipBuffer
  1645. private Tuple<ClipAction, CoreRow[]>? ClipBuffer;
  1646. protected void ResetClipBuffer()
  1647. {
  1648. ClipBuffer = null;
  1649. }
  1650. protected void SetClipBuffer(ClipAction action, CoreRow[] rows)
  1651. {
  1652. ClipBuffer = new Tuple<ClipAction, CoreRow[]>(action, rows);
  1653. }
  1654. private void CutToClipBuffer()
  1655. {
  1656. SetClipBuffer(ClipAction.Cut, SelectedRows);
  1657. InvalidateGrid();
  1658. }
  1659. private void CopyToClipBuffer()
  1660. {
  1661. SetClipBuffer(ClipAction.Copy, SelectedRows);
  1662. InvalidateGrid();
  1663. }
  1664. private void PasteFromClipBuffer()
  1665. {
  1666. if (ClipBuffer == null)
  1667. return;
  1668. if (!IsSequenced)
  1669. return;
  1670. using (new WaitCursor())
  1671. {
  1672. var updates = ClipBuffer.Item2.Select(x => x.ToObject<T>()).ToList();
  1673. if (BeforePaste(updates, ClipBuffer.Item1))
  1674. {
  1675. var currow = SelectedRows.FirstOrDefault()
  1676. ?? Data.Rows.LastOrDefault();
  1677. var sequence = currow != null ? currow.Get<T, long>(c => ((ISequenceable)c).Sequence) : 0;
  1678. var postrows = Data.Rows.Where(r => !ClipBuffer.Item2.Contains(r) && r.Get<ISequenceable, long>(x => x.Sequence) >= sequence);
  1679. updates.AddRange(LoadItems(postrows.ToArray()));
  1680. foreach (var update in updates)
  1681. {
  1682. sequence++;
  1683. ((ISequenceable)update).Sequence = sequence;
  1684. }
  1685. }
  1686. if (updates.Any())
  1687. {
  1688. SaveItems(updates.ToArray());
  1689. Refresh(false, true);
  1690. }
  1691. }
  1692. }
  1693. protected virtual bool BeforePaste(IEnumerable<T> items, ClipAction action)
  1694. {
  1695. return true;
  1696. }
  1697. private void Cut_Click(object sender, RoutedEventArgs e)
  1698. {
  1699. CutToClipBuffer();
  1700. }
  1701. private void Copy_Click(object sender, RoutedEventArgs e)
  1702. {
  1703. CopyToClipBuffer();
  1704. }
  1705. private void Paste_Click(object sender, RoutedEventArgs e)
  1706. {
  1707. PasteFromClipBuffer();
  1708. }
  1709. #endregion
  1710. protected virtual void ObjectToRow(T obj, CoreRow row)
  1711. {
  1712. row.Table.LoadRow(row, obj);
  1713. }
  1714. #region Import / Export
  1715. protected virtual CoreTable LoadImportKeys(String[] fields)
  1716. {
  1717. var result = new CoreTable();
  1718. result.LoadColumns(new Columns<T>(fields));
  1719. return result;
  1720. }
  1721. protected virtual Guid GetImportID()
  1722. {
  1723. return Guid.Empty;
  1724. }
  1725. protected virtual bool CustomiseImportItem(T item)
  1726. {
  1727. if (IsSequenced)
  1728. ((ISequenceable)item).Sequence = CoreUtils.GenerateSequence();
  1729. return true;
  1730. }
  1731. protected virtual string CustomiseImportFileName(string filename)
  1732. {
  1733. return filename;
  1734. }
  1735. protected virtual void DoImport()
  1736. {
  1737. var list = new DynamicImportList(
  1738. typeof(T),
  1739. GetImportID()
  1740. );
  1741. list.OnImportItem += o => { return CustomiseImportItem((T)o); };
  1742. list.OnCustomiseImport += (o, args) => { args.FileName = CustomiseImportFileName(args.FileName); };
  1743. list.OnSave += (sender, entity) => SaveItem(entity as T);
  1744. list.OnLoad += (sender, type, fields, id) => LoadImportKeys(fields);
  1745. list.ShowDialog();
  1746. Refresh(false, true);
  1747. }
  1748. private void Import_Click(object sender, RoutedEventArgs e)
  1749. {
  1750. DoImport();
  1751. }
  1752. protected virtual void CustomiseExportColumns(List<string> columnnames)
  1753. {
  1754. }
  1755. protected virtual string CustomiseExportFileName(string filename)
  1756. {
  1757. return filename;
  1758. }
  1759. protected virtual void CustomiseExportFilters(Filters<T> filters, CoreRow[] visiblerows)
  1760. {
  1761. }
  1762. protected virtual void ApplyExportFilter(CoreTable table, object data)
  1763. {
  1764. }
  1765. private static bool FilterByPredicate(CoreRow row, string column, FilterPredicate predicate)
  1766. {
  1767. var value = row[column];
  1768. var vStr = value?.ToString() ?? "";
  1769. var pValue = predicate.FilterValue;
  1770. var pStr = pValue?.ToString() ?? "";
  1771. return predicate.FilterType switch
  1772. {
  1773. FilterType.Contains => vStr.Contains(pStr),
  1774. FilterType.EndsWith => vStr.EndsWith(pStr),
  1775. FilterType.Equals => vStr.Equals(pStr),
  1776. FilterType.GreaterThan => vStr.CompareTo(pStr) > 0,
  1777. FilterType.GreaterThanOrEqual => vStr.CompareTo(pStr) >= 0,
  1778. FilterType.LessThan => vStr.CompareTo(pStr) < 0,
  1779. FilterType.LessThanOrEqual => vStr.CompareTo(pStr) <= 0,
  1780. FilterType.NotContains => !vStr.Contains(pStr),
  1781. FilterType.NotEndsWith => !vStr.EndsWith(pStr),
  1782. FilterType.NotEquals => !vStr.Equals(pStr),
  1783. FilterType.NotStartsWith => !vStr.StartsWith(pStr),
  1784. FilterType.StartsWith => vStr.StartsWith(pStr),
  1785. _ => true,
  1786. };
  1787. }
  1788. protected virtual void DoExport()
  1789. {
  1790. var columnnames = VisibleColumns.Select(x => x.ColumnName).ToList();
  1791. CustomiseExportColumns(columnnames);
  1792. var form = new DynamicExportForm(typeof(T), columnnames);
  1793. if (form.ShowDialog() != true)
  1794. return;
  1795. var filters = new Filters<T>();
  1796. filters.Add(DefineFilter());
  1797. var predicates = UIComponent.GetFilterPredicates();
  1798. var visiblerows = GetVisibleRows();
  1799. CustomiseExportFilters(filters, visiblerows);
  1800. var columns = new Columns<T>(form.Fields);
  1801. var otherColumns = form.GetChildFields()
  1802. .Select(x => new Tuple<Type, IColumns>(
  1803. x.Key,
  1804. (Activator.CreateInstance(typeof(Columns<>).MakeGenericType(x.Key), new object[] { x.Value }) as IColumns)!))
  1805. .Where(x => x.Item2.ColumnNames().Any()).ToList();
  1806. var reloadColumns = new Columns<T>();
  1807. foreach (var column in columns.ColumnNames())
  1808. {
  1809. reloadColumns.Add(column);
  1810. }
  1811. foreach (var column in HiddenColumns.ColumnNames)
  1812. {
  1813. reloadColumns.Add(column);
  1814. }
  1815. foreach (var (column, _) in predicates)
  1816. {
  1817. reloadColumns.Add(column);
  1818. }
  1819. var sort = LookupFactory.DefineSort<T>();
  1820. Reload(filters, reloadColumns, ref sort, (data, err) => Dispatcher.Invoke(() =>
  1821. {
  1822. if (data is not null)
  1823. {
  1824. var newData = new CoreTable();
  1825. foreach (var column in columns.Items)
  1826. newData.Columns.Add(new CoreColumn { ColumnName = column.Property, DataType = column.Type });
  1827. FilterRows(data, newData, filter: (row) =>
  1828. {
  1829. foreach (var (column, predicate) in predicates)
  1830. {
  1831. if (!FilterByPredicate(row, column, predicate))
  1832. {
  1833. return false;
  1834. }
  1835. }
  1836. return true;
  1837. });
  1838. var list = new List<Tuple<Type?, CoreTable>>() { new(typeof(T), newData) };
  1839. list.AddRange(LoadExportTables(filters, otherColumns));
  1840. DoExportTables(list);
  1841. }
  1842. else if (err is not null)
  1843. {
  1844. Logger.Send(LogType.Error, "", $"Error in export: {CoreUtils.FormatException(err)}");
  1845. MessageBox.Show(err.Message);
  1846. }
  1847. }));
  1848. }
  1849. private void Export_Click(object sender, RoutedEventArgs e)
  1850. {
  1851. DoExport();
  1852. }
  1853. /// <summary>
  1854. /// Loads the child tables for an export, based on the filter of the parent table.
  1855. /// </summary>
  1856. /// <remarks>
  1857. /// If not overriden, defaults to creating empty tables with no records.
  1858. /// </remarks>
  1859. /// <param name="filter">Filter for the parent table.</param>
  1860. /// <param name="tableColumns">A list of the child table types, with columns to load for each</param>
  1861. /// <returns>A list of tables, in the same order as they came in <paramref name="tableColumns"/></returns>
  1862. protected virtual IEnumerable<Tuple<Type?, CoreTable>> LoadExportTables(Filters<T> filter, IEnumerable<Tuple<Type, IColumns>> tableColumns)
  1863. {
  1864. return tableColumns.Select(x =>
  1865. {
  1866. var table = new CoreTable();
  1867. table.LoadColumns(x.Item2);
  1868. return new Tuple<Type?, CoreTable>(x.Item1, table);
  1869. });
  1870. }
  1871. private void DoExportTables(List<Tuple<Type?, CoreTable>> data)
  1872. {
  1873. var filename = CustomiseExportFileName(typeof(T).EntityName().Split('.').Last());
  1874. ExcelExporter.DoExport(data, filename);
  1875. }
  1876. #endregion
  1877. public void ScrollIntoView(CoreRow row)
  1878. {
  1879. UIComponent.ScrollIntoView(row);
  1880. }
  1881. #endregion
  1882. #region Custom Buttons
  1883. private Button CreateButton(BitmapImage? image = null, string? text = null, string? tooltip = null)
  1884. {
  1885. var button = new Button();
  1886. button.SetValue(BorderBrushProperty, new SolidColorBrush(Colors.Gray));
  1887. button.SetValue(BorderThicknessProperty, new Thickness(0.75));
  1888. button.Height = 30;
  1889. UpdateButton(button, image, text, tooltip);
  1890. return button;
  1891. }
  1892. public void UpdateButton(Button button, BitmapImage? image, string? text, string? tooltip = null)
  1893. {
  1894. var stackPnl = new StackPanel();
  1895. stackPnl.Orientation = Orientation.Horizontal;
  1896. //stackPnl.Margin = new Thickness(2);
  1897. if (image != null)
  1898. {
  1899. var img = new Image();
  1900. img.Source = image;
  1901. img.Margin = new Thickness(2);
  1902. img.ToolTip = tooltip;
  1903. stackPnl.Children.Add(img);
  1904. }
  1905. if (!string.IsNullOrEmpty(text))
  1906. {
  1907. button.MaxWidth = double.MaxValue;
  1908. var lbl = new Label();
  1909. lbl.Content = text;
  1910. lbl.VerticalAlignment = VerticalAlignment.Stretch;
  1911. lbl.VerticalContentAlignment = VerticalAlignment.Center;
  1912. lbl.Margin = new Thickness(2, 0, 5, 0);
  1913. lbl.ToolTip = ToolTip;
  1914. stackPnl.Children.Add(lbl);
  1915. }
  1916. else
  1917. button.MaxWidth = 30;
  1918. button.Content = stackPnl;
  1919. button.ToolTip = tooltip;
  1920. }
  1921. private bool bFirstButtonAdded = true;
  1922. private bool AnyButtonsVisible()
  1923. {
  1924. if (Add.Visibility != Visibility.Collapsed)
  1925. return true;
  1926. if (Edit.Visibility != Visibility.Collapsed)
  1927. return true;
  1928. /*if (MultiEdit.Visibility != Visibility.Collapsed)
  1929. return true;*/
  1930. if (Export.Visibility != Visibility.Collapsed)
  1931. return true;
  1932. return false;
  1933. }
  1934. public Button AddButton(string? caption, BitmapImage? image, string? tooltip, DynamicGridButtonClickEvent action, DynamicGridButtonPosition position = DynamicGridButtonPosition.Left)
  1935. {
  1936. var button = CreateButton(image, caption, tooltip);
  1937. button.Margin = position == DynamicGridButtonPosition.Right
  1938. ? new Thickness(2, 2, 0, 0)
  1939. : bFirstButtonAdded && AnyButtonsVisible()
  1940. ? new Thickness(0, 2, 0, 0)
  1941. : new Thickness(0, 2, 2, 0);
  1942. button.Padding = !String.IsNullOrWhiteSpace(caption) ? new Thickness(5, 1, 5, 1) : new Thickness(1);
  1943. button.Tag = action;
  1944. button.Click += Button_Click;
  1945. if (position == DynamicGridButtonPosition.Right)
  1946. RightButtonStack.Children.Add(button);
  1947. else
  1948. LeftButtonStack.Children.Add(button);
  1949. bFirstButtonAdded = false;
  1950. return button;
  1951. }
  1952. public Button AddButton(string? caption, BitmapImage? image, DynamicGridButtonClickEvent action, DynamicGridButtonPosition position = DynamicGridButtonPosition.Left)
  1953. {
  1954. var result = AddButton(caption, image, null, action, position);
  1955. return result;
  1956. }
  1957. private void Button_Click(object sender, RoutedEventArgs e)
  1958. {
  1959. var button = (Button)sender;
  1960. var action = (DynamicGridButtonClickEvent)button.Tag;
  1961. //CoreRow row = (CurrentRow > -1) && (CurrentRow < Data.Rows.Count) ? Data.Rows[this.CurrentRow] : null;
  1962. if (action.Invoke(button, SelectedRows))
  1963. Refresh(false, true);
  1964. }
  1965. #endregion
  1966. #region Header Actions
  1967. private void SelectColumnsClick()
  1968. {
  1969. var editor = new DynamicGridColumnsEditor(typeof(T));
  1970. editor.DirectEdit = IsDirectEditMode();
  1971. editor.Columns.AddRange(VisibleColumns);
  1972. if (editor.ShowDialog().Equals(true))
  1973. {
  1974. VisibleColumns.Clear();
  1975. VisibleColumns.AddRange(editor.Columns);
  1976. SaveColumns(VisibleColumns);
  1977. //OnSaveColumns?.Invoke(this, editor.Columns);
  1978. Refresh(true, true);
  1979. }
  1980. }
  1981. #endregion
  1982. #region Drag + Drop
  1983. /// <summary>
  1984. /// Handle a number of rows from a different <see cref="DynamicGrid{T}"/> being dragged into this one.
  1985. /// </summary>
  1986. /// <param name="entity">The type of entity that that the rows of <paramref name="table"/> represent.</param>
  1987. /// <param name="table">The data being dragged.</param>
  1988. /// <param name="e"></param>
  1989. protected virtual void OnDragEnd(Type entity, CoreTable table, DragEventArgs e)
  1990. {
  1991. Logger.Send(LogType.Information,"","OnDragEnd");
  1992. }
  1993. /// <summary>
  1994. /// Handle all types of items being dragged onto this grid that aren't handled by <see cref="OnDragEnd(Type, CoreTable, DragEventArgs)"/>,
  1995. /// i.e., data which is not a <see cref="CoreTable"/> from another <see cref="DynamicGrid{T}"/>
  1996. /// </summary>
  1997. /// <remarks>
  1998. /// Can be used to handle files, for example.
  1999. /// </remarks>
  2000. /// <param name="sender"></param>
  2001. /// <param name="e"></param>
  2002. protected virtual void HandleDragDrop(object sender, DragEventArgs e)
  2003. {
  2004. }
  2005. protected virtual void HandleDragOver(object sender, DragEventArgs e)
  2006. {
  2007. }
  2008. protected DragDropEffects DragTable(Type entity, CoreTable table)
  2009. {
  2010. Logger.Send(LogType.Information, "", "DragTable");
  2011. var data = new DataObject();
  2012. data.SetData(DynamicGridUtils.DragFormat, new DynamicGridDragFormat(table.ToDataTable(), entity));
  2013. var effect = DragDrop.DoDragDrop(this, data, DragDropEffects.All);
  2014. return effect;
  2015. }
  2016. protected virtual DragDropEffects OnRowsDragStart(CoreRow[] rows)
  2017. {
  2018. Logger.Send(LogType.Information, "", "OnRowsDragStart");
  2019. var table = new CoreTable();
  2020. table.LoadColumns(Data.Columns);
  2021. table.LoadRows(rows);
  2022. return DragTable(typeof(T), table);
  2023. }
  2024. #endregion
  2025. }