DynamicGrid.cs 76 KB

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