DynamicGrid.cs 75 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440
  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. public virtual void Refresh(bool reloadcolumns, bool reloaddata)
  783. {
  784. if (bRefreshing)
  785. return;
  786. if (!DoBeforeRefresh())
  787. return;
  788. UIComponent.BeforeRefresh();
  789. var cursor = UseWaitCursor ? new WaitCursor() : null;
  790. Loading.Visibility = Visibility.Visible;
  791. Loading.BeginAnimation(Label.OpacityProperty, LoadingFader);
  792. bRefreshing = true;
  793. if (reloadcolumns)
  794. ReloadColumns();
  795. if (reloaddata)
  796. {
  797. _lookupcache.Clear();
  798. var criteria = new Filters<T>();
  799. var filter = DefineFilter();
  800. if (filter != null)
  801. criteria.Add(filter);
  802. var columns = DataColumns();
  803. var sort = LookupFactory.DefineSort<T>();
  804. if (sort == null && IsSequenced)
  805. sort = new SortOrder<T>("Sequence");
  806. Reload(
  807. criteria
  808. , columns
  809. , ref sort
  810. , (table, exception) =>
  811. {
  812. if (exception != null)
  813. {
  814. Dispatcher.Invoke(() =>
  815. {
  816. MessageWindow.ShowError("Sorry! We couldn't load the data.", exception);
  817. });
  818. }
  819. else if (table is not null)
  820. {
  821. MasterData = table;
  822. Dispatcher.Invoke(() =>
  823. {
  824. ProcessData();
  825. DoAfterRefresh();
  826. bRefreshing = false;
  827. IsReady = true;
  828. });
  829. }
  830. }
  831. );
  832. }
  833. else
  834. {
  835. ProcessData();
  836. DoAfterRefresh();
  837. bRefreshing = false;
  838. IsReady = true;
  839. Loading.BeginAnimation(Label.OpacityProperty, null);
  840. Loading.Visibility = Visibility.Collapsed;
  841. }
  842. if (cursor != null)
  843. {
  844. cursor.Dispose();
  845. cursor = null;
  846. }
  847. }
  848. protected void NotifyBeforeRefresh(BeforeRefreshEventArgs args) => BeforeRefresh?.Invoke(this, args);
  849. protected void NotifyAfterRefresh(AfterRefreshEventArgs args) => AfterRefresh?.Invoke(this, args);
  850. protected bool OnBeforeRefresh()
  851. {
  852. return true;
  853. }
  854. private bool DoBeforeRefresh()
  855. {
  856. var result = OnBeforeRefresh();
  857. if (result)
  858. {
  859. var args = new BeforeRefreshEventArgs() { Cancel = false };
  860. NotifyBeforeRefresh(args);
  861. result = args.Cancel == false;
  862. }
  863. return result;
  864. }
  865. protected virtual void OnAfterRefresh()
  866. {
  867. }
  868. protected void DoAfterRefresh()
  869. {
  870. OnAfterRefresh();
  871. NotifyAfterRefresh(new AfterRefreshEventArgs());
  872. }
  873. public Columns<T> DataColumns()
  874. {
  875. var columns = Columns.None<T>();
  876. foreach (var column in VisibleColumns)
  877. columns.Add(column.ColumnName);
  878. foreach (var column in HiddenColumns.ColumnNames)
  879. columns.Add(new Column<T>(column));
  880. return columns;
  881. }
  882. private void ProcessData()
  883. {
  884. Data.Columns.Clear();
  885. Data.Setters.Clear();
  886. if (MasterData != null)
  887. foreach (var column in MasterData.Columns)
  888. Data.Columns.Add(column);
  889. LoadData();
  890. }
  891. protected readonly Dictionary<CoreRow, CoreRow> _recordmap = new();
  892. public void UpdateRow<TRow, TType>(CoreRow row, Expression<Func<TRow, TType>> column, TType value, bool refresh = true)
  893. {
  894. row.Set(column, value);
  895. _recordmap[row].Set(column, value);
  896. if (refresh)
  897. InvalidateRow(row);
  898. }
  899. public void UpdateRow<TType>(CoreRow row, string column, TType value, bool refresh = true)
  900. {
  901. row.Set(column, value);
  902. _recordmap[row].Set(column, value);
  903. if (refresh)
  904. InvalidateRow(row);
  905. }
  906. public void UpdateRow(CoreRow row, T obj)
  907. {
  908. ObjectToRow(obj, row);
  909. ObjectToRow(obj, _recordmap[row]);
  910. }
  911. public void AddRow(CoreRow row)
  912. {
  913. if (MasterData is null) return;
  914. var masterrow = MasterData.NewRow();
  915. MasterData.FillRow(masterrow, row);
  916. Refresh(false, false);
  917. }
  918. public void AddRow(T data)
  919. {
  920. if (MasterData is null) return;
  921. MasterData.LoadRow(data);
  922. Refresh(false, false);
  923. }
  924. public void DeleteRow(CoreRow row)
  925. {
  926. if (MasterData is null) return;
  927. var masterrow = _recordmap[row];
  928. MasterData.Rows.Remove(masterrow);
  929. Refresh(false, false);
  930. }
  931. private void FilterRows(CoreTable from, CoreTable into, Dictionary<CoreRow, CoreRow>? recordMap = null, Func<CoreRow, bool>? filter = null)
  932. {
  933. into.Rows.Clear();
  934. recordMap?.Clear();
  935. foreach (var row in from.Rows.ToArray())
  936. if (FilterRecord(row) && filter?.Invoke(row) != false)
  937. {
  938. var newrow = into.NewRow();
  939. for (var i = 0; i < into.Columns.Count; i++)
  940. {
  941. var value = i < row.Values.Count ? row.Values[i] : null;
  942. if (into.Columns[i].DataType.IsNumeric())
  943. value = into.Columns[i].DataType.IsDefault(value) ? null : value;
  944. //else if (Data.Columns[i].DataType == typeof(String[]))
  945. // value = String.Join("\n", value as String[]);
  946. newrow.Values.Add(value);
  947. }
  948. //newrow.Values.AddRange(row.Values);
  949. //if ((OnFilterRecord == null) || (OnFilterRecord(row)))
  950. into.Rows.Add(newrow);
  951. recordMap?.TryAdd(newrow, row);
  952. }
  953. }
  954. private void LoadData()
  955. {
  956. ResetClipBuffer();
  957. if (MasterData is null)
  958. return;
  959. FilterRows(MasterData, Data, _recordmap);
  960. InvalidateGrid();
  961. //ScrollBar.Value = _CurrentRow <= 0 ? 0 : _CurrentRow;
  962. SelectedRows = Array.Empty<CoreRow>();
  963. }
  964. //IncrementalList<T> _data = null;
  965. public void InvalidateRow(CoreRow row)
  966. {
  967. UIComponent.InvalidateRow(row);
  968. }
  969. protected void InvalidateGrid()
  970. {
  971. if (RowStyleSelector != null)
  972. RowStyleSelector.Data = Data;
  973. UIComponent.RefreshData(Data);
  974. Loading.BeginAnimation(Label.OpacityProperty, null);
  975. Loading.Visibility = Visibility.Collapsed;
  976. }
  977. public void AddVisualFilter(string column, string value, FilterType filtertype = FilterType.Contains)
  978. {
  979. UIComponent.AddVisualFilter(column, value, filtertype);
  980. }
  981. protected List<Tuple<string, Func<CoreRow, bool>>> GetFilterPredicates()
  982. {
  983. return UIComponent.GetFilterPredicates();
  984. }
  985. #endregion
  986. #region Item Manipulation
  987. #region Load/Save/Delete
  988. public virtual T[] LoadItems(CoreRow[] rows)
  989. {
  990. var result = new List<T>();
  991. foreach (var row in rows)
  992. {
  993. var index = Data.Rows.IndexOf(row);
  994. result.Add(LoadItem(row));
  995. }
  996. return result.ToArray();
  997. }
  998. public abstract T LoadItem(CoreRow row);
  999. public abstract void SaveItem(T item);
  1000. public virtual void SaveItems(T[] items)
  1001. {
  1002. foreach (var item in items)
  1003. SaveItem(item);
  1004. }
  1005. protected virtual bool CanDeleteItems(params CoreRow[] rows)
  1006. {
  1007. return true;
  1008. }
  1009. public abstract void DeleteItems(params CoreRow[] rows);
  1010. protected virtual void DoDelete()
  1011. {
  1012. var rows = SelectedRows.ToArray();
  1013. if (rows.Any())
  1014. if (CanDeleteItems(rows))
  1015. if (MessageBox.Show("Are you sure you wish to delete the selected records?", "Confirm Delete", MessageBoxButton.YesNo) ==
  1016. MessageBoxResult.Yes)
  1017. {
  1018. DeleteItems(rows);
  1019. SelectedRows = Array.Empty<CoreRow>();
  1020. OnChanged?.Invoke(this, EventArgs.Empty);
  1021. Refresh(false, true);
  1022. SelectItems(null);
  1023. }
  1024. }
  1025. private void Delete_Click(object sender, RoutedEventArgs e)
  1026. {
  1027. DoDelete();
  1028. }
  1029. #endregion
  1030. #region Edit
  1031. protected virtual void DoEdit()
  1032. {
  1033. if (SelectedRows.Length == 0)
  1034. return;
  1035. if (AddEditClick(SelectedRows))
  1036. {
  1037. SelectItems(SelectedRows);
  1038. }
  1039. }
  1040. private void Edit_Click(object sender, RoutedEventArgs e)
  1041. {
  1042. DoEdit();
  1043. }
  1044. protected virtual void DoAdd(bool OpenEditorOnDirectEdit = false)
  1045. {
  1046. //CoreRow row = (SelectedRow > -1) && (SelectedRow < Data.Rows.Count) ? Data.Rows[this.SelectedRow] : null;
  1047. if (IsDirectEditMode() && !OpenEditorOnDirectEdit)
  1048. {
  1049. CreateItems(null);
  1050. }
  1051. else if (AddEditClick(null))
  1052. {
  1053. Refresh(false, true);
  1054. }
  1055. }
  1056. protected void CreateItems(Func<IEnumerable<T>>? create)
  1057. {
  1058. var newRows = new List<CoreRow>();
  1059. var items = create?.Invoke() ?? CoreUtils.One(CreateItem());
  1060. foreach (var item in items)
  1061. {
  1062. if (!AfterCreate(item))
  1063. return;
  1064. SaveItem(item);
  1065. var datarow = Data.NewRow();
  1066. ObjectToRow(item, datarow);
  1067. Data.Rows.Add(datarow);
  1068. newRows.Add(datarow);
  1069. var masterrow = MasterData.NewRow();
  1070. ObjectToRow(item, masterrow);
  1071. MasterData.Rows.Add(masterrow);
  1072. _recordmap[datarow] = masterrow;
  1073. }
  1074. InvalidateGrid();
  1075. SelectedRows = newRows.ToArray();
  1076. OnChanged?.Invoke(this, EventArgs.Empty);
  1077. }
  1078. private void Add_Click(object sender, RoutedEventArgs e)
  1079. {
  1080. if (CanCreateItems())
  1081. DoAdd();
  1082. }
  1083. public virtual DynamicEditorPages LoadEditorPages(T item)
  1084. {
  1085. DynamicEditorPages pages = new DynamicEditorPages();
  1086. DynamicGridUtils.LoadOneToManyPages(typeof(T), pages);
  1087. DynamicGridUtils.LoadEnclosedListPages(typeof(T), pages);
  1088. DynamicGridUtils.LoadManyToManyPages(typeof(T), pages);
  1089. DynamicGridUtils.LoadCustomEditorPages(typeof(T), pages);
  1090. foreach (var page in pages)
  1091. page.Ready = false;
  1092. return pages;
  1093. }
  1094. public virtual void LoadEditorButtons(T item, DynamicEditorButtons buttons)
  1095. {
  1096. buttons.Clear();
  1097. buttons.Add(
  1098. "",
  1099. Wpf.Resources.help.AsBitmapImage(),
  1100. item,
  1101. (f, i) =>
  1102. {
  1103. Process.Start(new ProcessStartInfo("https://prsdigital.com.au/wiki/index.php/" + typeof(T).Name.SplitCamelCase().Replace(" ", "_"))
  1104. { UseShellExecute = true });
  1105. }
  1106. );
  1107. OnLoadEditorButtons?.Invoke(item, buttons);
  1108. }
  1109. protected virtual void BeforeLoad(IDynamicEditorForm form, T[] items)
  1110. {
  1111. form.BeforeLoad();
  1112. }
  1113. void IDynamicGrid.InitialiseEditorForm(IDynamicEditorForm editor, object[] items, Func<Type, CoreTable>? pageDataHandler, bool preloadPages)
  1114. {
  1115. InitialiseEditorForm(editor, items.Cast<T>().ToArray(), pageDataHandler, preloadPages);
  1116. }
  1117. public virtual bool EditItems(object[] items, Func<Type, CoreTable?>? PageDataHandler = null, bool PreloadPages = false)
  1118. {
  1119. var values = items.Cast<T>().ToArray();
  1120. return EditItems(values, PageDataHandler, PreloadPages);
  1121. }
  1122. public virtual void InitialiseEditorForm(IDynamicEditorForm editor, T[] items, Func<Type, CoreTable?>? pageDataHandler = null, bool preloadPages = false)
  1123. {
  1124. var pages = items.Length == 1 ? LoadEditorPages(items.First()) : new DynamicEditorPages();
  1125. var buttons = new DynamicEditorButtons();
  1126. if (items.Length == 1)
  1127. LoadEditorButtons(items.First(), buttons);
  1128. editor.Setup(items.Any() ? items.First().GetType() : typeof(T), pages, buttons, pageDataHandler, preloadPages);
  1129. editor.OnCustomiseColumns = (sender, columns) =>
  1130. {
  1131. columns.Clear();
  1132. columns.AddRange(MasterColumns);
  1133. };
  1134. editor.OnDefineEditor = (o, c) =>
  1135. {
  1136. var result = GetEditor(o, c);
  1137. if (result != null)
  1138. result = result.CloneEditor();
  1139. return result;
  1140. };
  1141. editor.OnFormCustomiseEditor += DoCustomiseEditor;
  1142. editor.OnDefineFilter = (type, column) => { return DefineLookupFilter(type, column, items); };
  1143. //editor.OnDefineFilter += (o, e) => { return DefineFilter(items, e); };
  1144. editor.OnDefineLookups = editor => DefineLookups(editor, items);
  1145. editor.OnEditorValueChanged += (s, n, v) => EditorValueChanged(editor, items, n, v);
  1146. editor.OnAfterEditorValueChanged += (g, args) => AfterEditorValueChanged(g, items, args);
  1147. editor.OnReconfigureEditors = g => DoReconfigureEditors(g, items);
  1148. editor.OnValidateData += (o, i) => ValidateData(items);
  1149. editor.OnSelectPage += SelectPage;
  1150. editor.OnSaveItem = (o, e) =>
  1151. {
  1152. try
  1153. {
  1154. using var Wait = new WaitCursor();
  1155. DoBeforeSave(editor, items);
  1156. if (items.Length == 1)
  1157. editor.UnloadEditorPages(false);
  1158. foreach (var item in items)
  1159. SaveItem(item);
  1160. if (items.Length == 1)
  1161. editor.UnloadEditorPages(true);
  1162. DoAfterSave(editor, items);
  1163. }
  1164. catch (Exception err)
  1165. {
  1166. MessageBox.Show(err.Message);
  1167. e.Cancel = true;
  1168. }
  1169. };
  1170. BeforeLoad(editor, items);
  1171. editor.Items = items;
  1172. AfterLoad(editor, items);
  1173. }
  1174. private void DoCustomiseEditor(IDynamicEditorForm sender, object[] items, DynamicGridColumn column, BaseEditor editor)
  1175. {
  1176. CustomiseEditor((T[])items, column, editor);
  1177. OnCustomiseEditor?.Invoke(sender, (T[])items, column, editor);
  1178. }
  1179. protected virtual void CustomiseEditor(T[] items, DynamicGridColumn column, BaseEditor editor)
  1180. {
  1181. }
  1182. protected virtual void DoAfterSave(IDynamicEditorForm editor, T[] items)
  1183. {
  1184. OnAfterSave?.Invoke(editor, items);
  1185. }
  1186. protected virtual void DoBeforeSave(IDynamicEditorForm editor, T[] items)
  1187. {
  1188. OnBeforeSave?.Invoke(editor, items);
  1189. }
  1190. public virtual bool EditItems(T[] items, Func<Type, CoreTable?>? PageDataHandler = null, bool PreloadPages = false)
  1191. {
  1192. DynamicEditorForm editor;
  1193. using (var cursor = new WaitCursor())
  1194. {
  1195. editor = new DynamicEditorForm();
  1196. editor.SetValue(Panel.ZIndexProperty, 999);
  1197. InitialiseEditorForm(editor, items, PageDataHandler, PreloadPages);
  1198. OnEditorLoaded?.Invoke(editor, items);
  1199. }
  1200. return editor.ShowDialog() == true;
  1201. }
  1202. private Dictionary<String, object?> AfterEditorValueChanged(DynamicEditorGrid grid, T[] items, AfterEditorValueChangedArgs args)
  1203. {
  1204. var changes = new Dictionary<string, object?>();
  1205. OnAfterEditorValueChanged(grid, items, args, changes);
  1206. return changes;
  1207. }
  1208. protected virtual void OnAfterEditorValueChanged(DynamicEditorGrid? grid, T[] items, AfterEditorValueChangedArgs args, Dictionary<String, object?> changes)
  1209. {
  1210. }
  1211. protected virtual void DoReconfigureEditors(DynamicEditorGrid grid, T[] items)
  1212. {
  1213. /*if (items.First() is IDimensioned dimensioned)
  1214. {
  1215. UpdateEditor(grid, x => x.Dimensions.Quantity, dimensioned.Dimensions.GetUnit().HasQuantity);
  1216. UpdateEditor(grid, x => x.Dimensions.Length, dimensioned.Dimensions.GetUnit().HasLength);
  1217. UpdateEditor(grid, x => x.Dimensions.Width, dimensioned.Dimensions.GetUnit().HasWidth);
  1218. UpdateEditor(grid, x => x.Dimensions.Height, dimensioned.Dimensions.GetUnit().HasHeight);
  1219. UpdateEditor(grid, x => x.Dimensions.Weight, dimensioned.Dimensions.GetUnit().HasWeight);
  1220. }*/
  1221. }
  1222. private List<string>? ValidateData(T[] items)
  1223. {
  1224. var errors = new List<string>();
  1225. DoValidate(items, errors);
  1226. OnValidate?.Invoke(this, items, errors);
  1227. return errors.Count != 0 ? errors : null;
  1228. }
  1229. protected virtual void DoValidate(T[] items, List<string> errors)
  1230. {
  1231. }
  1232. protected virtual void AfterLoad(IDynamicEditorForm editor, T[] items)
  1233. {
  1234. editor.AfterLoad();
  1235. }
  1236. protected virtual void SelectPage(object sender, BaseObject[]? items)
  1237. {
  1238. }
  1239. protected virtual Dictionary<string, object?> EditorValueChanged(IDynamicEditorForm editor, T[] items, string name, object value)
  1240. {
  1241. var result = DynamicGridUtils.UpdateEditorValue(items, name, value);
  1242. if (OnEditorValueChanged != null)
  1243. {
  1244. var newchanges = OnEditorValueChanged(editor, name, value);
  1245. foreach (var key in newchanges.Keys)
  1246. result[key] = newchanges[key];
  1247. }
  1248. return result;
  1249. }
  1250. private readonly Dictionary<Tuple<Type, Type>, Dictionary<object, object>> _lookupcache = new();
  1251. protected virtual void DefineLookups(ILookupEditorControl sender, T[] items, bool async = true)
  1252. {
  1253. if (sender.EditorDefinition is not ILookupEditor editor)
  1254. return;
  1255. var colname = sender.ColumnName;
  1256. if (async)
  1257. {
  1258. Task.Run(() =>
  1259. {
  1260. try
  1261. {
  1262. var values = editor.Values(typeof(T), colname, items);
  1263. Dispatcher.Invoke(
  1264. () =>
  1265. {
  1266. try
  1267. {
  1268. //Logger.Send(LogType.Information, typeof(T).Name, "Dispatching Results" + colname);
  1269. sender.LoadLookups(values);
  1270. }
  1271. catch (Exception e2)
  1272. {
  1273. Logger.Send(LogType.Information, typeof(T).Name,
  1274. "Exception (2) in LoadLookups: " + e2.Message + "\n" + e2.StackTrace);
  1275. }
  1276. }
  1277. );
  1278. }
  1279. catch (Exception e)
  1280. {
  1281. Logger.Send(LogType.Information, typeof(T).Name,
  1282. "Exception (1) in LoadLookups: " + e.Message + "\n" + e.StackTrace);
  1283. }
  1284. });
  1285. }
  1286. else
  1287. {
  1288. var values = editor.Values(typeof(T), colname, items);
  1289. sender.LoadLookups(values);
  1290. }
  1291. }
  1292. /// <summary>
  1293. /// Retrieves an editor to display for the given column of <paramref name="item"/>.
  1294. /// </summary>
  1295. /// <param name="item">The object being edited.</param>
  1296. /// <param name="column">The column of the editor.</param>
  1297. /// <returns>A new editor, or <see langword="null"/> if no editor defined and no sensible default exists.</returns>
  1298. protected virtual BaseEditor? GetEditor(object item, DynamicGridColumn column)
  1299. {
  1300. return column.Editor ?? CoreUtils.GetProperty(item.GetType(), column.ColumnName).GetEditor();
  1301. }
  1302. protected IFilter? DefineLookupFilter(Type type, string column, T[] items)
  1303. {
  1304. return LookupFactory.DefineLookupFilter(typeof(T), type, column, items);
  1305. }
  1306. protected virtual void SetEditorValue(object item, string name, object value)
  1307. {
  1308. try
  1309. {
  1310. CoreUtils.SetPropertyValue(item, name, value);
  1311. }
  1312. catch (Exception e)
  1313. {
  1314. Logger.Send(LogType.Error, "", string.Format("*** Unknown Error: {0}\n{1}", e.Message, e.StackTrace));
  1315. }
  1316. }
  1317. protected virtual object? GetEditorValue(object item, string name)
  1318. {
  1319. return CoreUtils.GetPropertyValue(item, name);
  1320. }
  1321. protected virtual bool CanCreateItems()
  1322. {
  1323. return true;
  1324. }
  1325. private bool AddEditClick(CoreRow[]? rows)
  1326. {
  1327. if (!IsEnabled || bRefreshing)
  1328. return false;
  1329. if (rows == null || rows.Length == 0)
  1330. {
  1331. if (!CanCreateItems())
  1332. return false;
  1333. var item = CreateItem();
  1334. if (!AfterCreate(item))
  1335. return false;
  1336. // Yea, and this won't work, because we're actually usually showing the description of a linked item,
  1337. // not the id of the link, and we need to set the ID to have it work properly :-(
  1338. //foreach (String key in VisualFilters.Keys)
  1339. // CoreUtils.SetPropertyValue(item, key, VisualFilters[key]);
  1340. if (EditItems([item]))
  1341. {
  1342. //_CurrentRow = Data.Rows.Count;
  1343. var row = Data.NewRow();
  1344. ObjectToRow(item, row);
  1345. Data.Rows.Add(row);
  1346. InvalidateGrid();
  1347. SelectedRows = [row];
  1348. DoChanged();
  1349. return true;
  1350. }
  1351. return false;
  1352. }
  1353. var items = Array.Empty<T>();
  1354. using (new WaitCursor())
  1355. {
  1356. Stopwatch sw = new Stopwatch();
  1357. sw.Start();
  1358. items = LoadItems(rows);
  1359. //Logger.Send(LogType.Information, "DG:LoadItems", String.Format("Loaded Items: {0}ms", sw.ElapsedMilliseconds));
  1360. sw.Stop();
  1361. }
  1362. if (items.Length != 0)
  1363. {
  1364. var snaps = items.ToArray(x => x.TakeSnapshot());
  1365. if (EditItems(items))
  1366. {
  1367. var sel = SelectedRows;
  1368. for (var i = 0; i < items.Length; i++)
  1369. UpdateRow(rows[i], items[i]);
  1370. InvalidateGrid();
  1371. SelectedRows = sel;
  1372. DoChanged();
  1373. return true;
  1374. }
  1375. else
  1376. {
  1377. foreach(var snap in snaps)
  1378. {
  1379. snap.ResetObject();
  1380. }
  1381. }
  1382. return false;
  1383. }
  1384. return false;
  1385. }
  1386. #endregion
  1387. #region Duplicate
  1388. protected virtual IEnumerable<T> LoadDuplicatorItems(CoreRow[] rows)
  1389. {
  1390. return LoadItems(rows);
  1391. }
  1392. private bool DoDuplicate(Button button, CoreRow[] rows)
  1393. {
  1394. if (!rows.Any())
  1395. {
  1396. MessageBox.Show("Please select at least one record to duplicate!");
  1397. return false;
  1398. }
  1399. /*var ids = ExtractValues(x => x.ID, Selection.Selected).ToArray();
  1400. if (!ids.Any())
  1401. {
  1402. MessageBox.Show("Please select at least one record to duplicate!");
  1403. return false;
  1404. }*/
  1405. var duplicator = (new T() as IDuplicatable)?.GetDuplicator();
  1406. if (duplicator is null)
  1407. {
  1408. MessageBox.Show($"Cannot duplicate {typeof(T)}");
  1409. return false;
  1410. }
  1411. duplicator.Duplicate(LoadDuplicatorItems(rows));// new Filter<T>(x => x.ID).InList(ids));
  1412. return true;
  1413. }
  1414. #endregion
  1415. public virtual T CreateItem()
  1416. {
  1417. var result = new T();
  1418. OnCreateItem?.Invoke(this, result);
  1419. return result;
  1420. }
  1421. public virtual bool AfterCreate(T item)
  1422. {
  1423. return OnAfterCreateItem?.Invoke(this, item) ?? true;
  1424. }
  1425. protected virtual void DoPrint(object sender)
  1426. {
  1427. OnPrintData?.Invoke(sender);
  1428. }
  1429. protected virtual void ShowHelp(string slug)
  1430. {
  1431. Process.Start(new ProcessStartInfo("https://prsdigital.com.au/wiki/index.php/" + slug) { UseShellExecute = true });
  1432. }
  1433. protected void ReloadForms<TTargetType, TTargetForm, TSourceForm>(IDynamicEditorForm editor, TTargetType item,
  1434. Expression<Func<TSourceForm, object?>> sourcekey, Guid sourceid)
  1435. where TTargetType : Entity, new()
  1436. where TTargetForm : Entity, IRemotable, IPersistent, IDigitalFormInstance, new()
  1437. where TSourceForm : Entity, IRemotable, IPersistent, IDigitalForm<TTargetType>, new()
  1438. {
  1439. var type = typeof(IDynamicOneToManyGrid<,>).MakeGenericType(typeof(TTargetType), typeof(TTargetForm));
  1440. var page =
  1441. editor.Pages?.FirstOrDefault(x => x.GetType().GetInterfaces().Contains(type)) as IDynamicOneToManyGrid<TTargetType, TTargetForm>;
  1442. if (page != null && item != null)
  1443. {
  1444. if (!page.Ready)
  1445. page.Load(item, null);
  1446. CoreTable table;
  1447. if (sourceid == Guid.Empty)
  1448. {
  1449. table = new CoreTable();
  1450. table.LoadColumns(typeof(TSourceForm));
  1451. }
  1452. else
  1453. {
  1454. table = new Client<TSourceForm>().Query(
  1455. new Filter<TSourceForm>(sourcekey).IsEqualTo(sourceid).And(x => x.Form.AppliesTo)
  1456. .IsEqualTo(typeof(TTargetType).EntityName().Split('.').Last())
  1457. );
  1458. }
  1459. var newforms = new List<TTargetForm>();
  1460. foreach (var row in table.Rows)
  1461. {
  1462. var sourceform = row.ToObject<TSourceForm>();
  1463. var targetform = new TTargetForm();
  1464. targetform.Form.ID = sourceform.Form.ID;
  1465. targetform.Form.Synchronise(sourceform.Form);
  1466. newforms.Add(targetform);
  1467. }
  1468. page.Items.Clear();
  1469. page.LoadItems(newforms.ToArray());
  1470. }
  1471. }
  1472. #region ClipBuffer
  1473. private Tuple<ClipAction, CoreRow[]>? ClipBuffer;
  1474. protected void ResetClipBuffer()
  1475. {
  1476. ClipBuffer = null;
  1477. }
  1478. protected void SetClipBuffer(ClipAction action, CoreRow[] rows)
  1479. {
  1480. ClipBuffer = new Tuple<ClipAction, CoreRow[]>(action, rows);
  1481. }
  1482. private void CutToClipBuffer()
  1483. {
  1484. SetClipBuffer(ClipAction.Cut, SelectedRows);
  1485. InvalidateGrid();
  1486. }
  1487. private void CopyToClipBuffer()
  1488. {
  1489. SetClipBuffer(ClipAction.Copy, SelectedRows);
  1490. InvalidateGrid();
  1491. }
  1492. private void PasteFromClipBuffer()
  1493. {
  1494. if (ClipBuffer == null)
  1495. return;
  1496. if (!ShowSequenceButtons)
  1497. return;
  1498. using (new WaitCursor())
  1499. {
  1500. var updates = ClipBuffer.Item2.Select(x => x.ToObject<T>()).ToList();
  1501. if (BeforePaste(updates, ClipBuffer.Item1))
  1502. {
  1503. var currow = SelectedRows.FirstOrDefault()
  1504. ?? Data.Rows.LastOrDefault();
  1505. var sequence = currow != null ? currow.Get<T, long>(c => ((ISequenceable)c).Sequence) : 0;
  1506. var postrows = Data.Rows.Where(r => !ClipBuffer.Item2.Contains(r) && r.Get<ISequenceable, long>(x => x.Sequence) >= sequence);
  1507. updates.AddRange(LoadItems(postrows.ToArray()));
  1508. foreach (var update in updates)
  1509. {
  1510. sequence++;
  1511. ((ISequenceable)update).Sequence = sequence;
  1512. }
  1513. }
  1514. if (updates.Any())
  1515. {
  1516. SaveItems(updates.ToArray());
  1517. Refresh(false, true);
  1518. }
  1519. }
  1520. }
  1521. protected virtual bool BeforePaste(IEnumerable<T> items, ClipAction action)
  1522. {
  1523. return true;
  1524. }
  1525. private void Cut_Click(object sender, RoutedEventArgs e)
  1526. {
  1527. CutToClipBuffer();
  1528. }
  1529. private void Copy_Click(object sender, RoutedEventArgs e)
  1530. {
  1531. CopyToClipBuffer();
  1532. }
  1533. private void Paste_Click(object sender, RoutedEventArgs e)
  1534. {
  1535. PasteFromClipBuffer();
  1536. }
  1537. #endregion
  1538. protected virtual void ObjectToRow(T obj, CoreRow row)
  1539. {
  1540. row.Table.FillRow(row, obj);
  1541. }
  1542. #region Import / Export
  1543. protected virtual CoreTable LoadImportKeys(String[] fields)
  1544. {
  1545. var result = new CoreTable();
  1546. result.LoadColumns(Columns.None<T>().Add(fields));
  1547. return result;
  1548. }
  1549. protected virtual Guid GetImportID()
  1550. {
  1551. return Guid.Empty;
  1552. }
  1553. protected virtual bool CustomiseImportItem(T item)
  1554. {
  1555. if (IsSequenced)
  1556. ((ISequenceable)item).Sequence = CoreUtils.GenerateSequence();
  1557. return true;
  1558. }
  1559. protected virtual string CustomiseImportFileName(string filename)
  1560. {
  1561. return filename;
  1562. }
  1563. protected virtual void DoImport()
  1564. {
  1565. var list = new DynamicImportList(
  1566. typeof(T),
  1567. GetImportID()
  1568. );
  1569. list.OnImportItem += o => { return CustomiseImportItem((T)o); };
  1570. list.OnCustomiseImport += (o, args) => { args.FileName = CustomiseImportFileName(args.FileName); };
  1571. list.OnSave += (sender, entity) => SaveItem(entity as T);
  1572. list.OnLoad += (sender, type, fields, id) => LoadImportKeys(fields);
  1573. list.ShowDialog();
  1574. Refresh(false, true);
  1575. }
  1576. private void Import_Click(object sender, RoutedEventArgs e)
  1577. {
  1578. DoImport();
  1579. }
  1580. protected virtual void CustomiseExportColumns(List<string> columnnames)
  1581. {
  1582. }
  1583. protected virtual string CustomiseExportFileName(string filename)
  1584. {
  1585. return filename;
  1586. }
  1587. protected virtual void CustomiseExportFilters(Filters<T> filters, CoreRow[] visiblerows)
  1588. {
  1589. }
  1590. protected virtual void ApplyExportFilter(CoreTable table, object data)
  1591. {
  1592. }
  1593. protected virtual void DoExport()
  1594. {
  1595. var columnnames = VisibleColumns.Select(x => x.ColumnName).ToList();
  1596. CustomiseExportColumns(columnnames);
  1597. var form = new DynamicExportForm(typeof(T), columnnames);
  1598. if (form.ShowDialog() != true)
  1599. return;
  1600. var filters = new Filters<T>();
  1601. filters.Add(DefineFilter());
  1602. var predicates = UIComponent.GetFilterPredicates();
  1603. var visiblerows = GetVisibleRows();
  1604. CustomiseExportFilters(filters, visiblerows);
  1605. var columns = Columns.None<T>().Add(form.Fields);
  1606. var otherColumns = form.GetChildFields()
  1607. .Select(x => new Tuple<Type, IColumns>(
  1608. x.Key,
  1609. Columns.None(x.Key).Add(x.Value)))
  1610. .Where(x => x.Item2.ColumnNames().Any()).ToList();
  1611. var reloadColumns = Columns.None<T>();
  1612. foreach (var column in columns)
  1613. {
  1614. reloadColumns.Add(column);
  1615. }
  1616. foreach (var column in HiddenColumns.ColumnNames)
  1617. {
  1618. reloadColumns.Add(column);
  1619. }
  1620. foreach (var (column, _) in predicates)
  1621. {
  1622. reloadColumns.Add(column);
  1623. }
  1624. var sort = LookupFactory.DefineSort<T>();
  1625. Reload(filters, reloadColumns, ref sort, (data, err) => Dispatcher.Invoke(() =>
  1626. {
  1627. if (data is not null)
  1628. {
  1629. var newData = new CoreTable();
  1630. newData.LoadColumns(columns);
  1631. FilterRows(data, newData, filter: row =>
  1632. {
  1633. foreach(var (_, predicate) in predicates)
  1634. {
  1635. if (!predicate(row))
  1636. {
  1637. return false;
  1638. }
  1639. }
  1640. return true;
  1641. });
  1642. var list = new List<Tuple<Type?, CoreTable>>() { new(typeof(T), newData) };
  1643. list.AddRange(LoadExportTables(filters, otherColumns));
  1644. DoExportTables(list);
  1645. }
  1646. else if (err is not null)
  1647. {
  1648. Logger.Send(LogType.Error, "", $"Error in export: {CoreUtils.FormatException(err)}");
  1649. MessageBox.Show(err.Message);
  1650. }
  1651. }));
  1652. }
  1653. private void Export_Click(object sender, RoutedEventArgs e)
  1654. {
  1655. DoExport();
  1656. }
  1657. /// <summary>
  1658. /// Loads the child tables for an export, based on the filter of the parent table.
  1659. /// </summary>
  1660. /// <remarks>
  1661. /// If not overriden, defaults to creating empty tables with no records.
  1662. /// </remarks>
  1663. /// <param name="filter">Filter for the parent table.</param>
  1664. /// <param name="tableColumns">A list of the child table types, with columns to load for each</param>
  1665. /// <returns>A list of tables, in the same order as they came in <paramref name="tableColumns"/></returns>
  1666. protected virtual IEnumerable<Tuple<Type?, CoreTable>> LoadExportTables(Filters<T> filter, IEnumerable<Tuple<Type, IColumns>> tableColumns)
  1667. {
  1668. return tableColumns.Select(x =>
  1669. {
  1670. var table = new CoreTable();
  1671. table.LoadColumns(x.Item2);
  1672. return new Tuple<Type?, CoreTable>(x.Item1, table);
  1673. });
  1674. }
  1675. private void DoExportTables(List<Tuple<Type?, CoreTable>> data)
  1676. {
  1677. var filename = CustomiseExportFileName(typeof(T).EntityName().Split('.').Last());
  1678. ExcelExporter.DoExport(data, filename);
  1679. }
  1680. #endregion
  1681. public void ScrollIntoView(CoreRow row)
  1682. {
  1683. UIComponent.ScrollIntoView(row);
  1684. }
  1685. #endregion
  1686. #region Custom Buttons
  1687. private Button CreateButton(BitmapImage? image = null, string? text = null, string? tooltip = null)
  1688. {
  1689. var button = new Button();
  1690. button.SetValue(BorderBrushProperty, new SolidColorBrush(Colors.Gray));
  1691. button.SetValue(BorderThicknessProperty, new Thickness(0.75));
  1692. button.Height = 30;
  1693. UpdateButton(button, image, text, tooltip);
  1694. return button;
  1695. }
  1696. public void UpdateButton(Button button, BitmapImage? image, string? text, string? tooltip = null)
  1697. {
  1698. var stackPnl = new StackPanel();
  1699. stackPnl.Orientation = Orientation.Horizontal;
  1700. //stackPnl.Margin = new Thickness(2);
  1701. if (image != null)
  1702. {
  1703. var img = new Image();
  1704. img.Source = image;
  1705. img.Margin = new Thickness(2);
  1706. img.ToolTip = tooltip;
  1707. stackPnl.Children.Add(img);
  1708. }
  1709. if (!string.IsNullOrEmpty(text))
  1710. {
  1711. button.MaxWidth = double.MaxValue;
  1712. var lbl = new Label();
  1713. lbl.Content = text;
  1714. lbl.VerticalAlignment = VerticalAlignment.Stretch;
  1715. lbl.VerticalContentAlignment = VerticalAlignment.Center;
  1716. lbl.Margin = new Thickness(2, 0, 5, 0);
  1717. lbl.ToolTip = ToolTip;
  1718. stackPnl.Children.Add(lbl);
  1719. }
  1720. else
  1721. button.MaxWidth = 30;
  1722. button.Content = stackPnl;
  1723. button.ToolTip = tooltip;
  1724. }
  1725. private bool bFirstButtonAdded = true;
  1726. private bool AnyButtonsVisible()
  1727. {
  1728. if (Add.Visibility != Visibility.Collapsed)
  1729. return true;
  1730. if (Edit.Visibility != Visibility.Collapsed)
  1731. return true;
  1732. /*if (MultiEdit.Visibility != Visibility.Collapsed)
  1733. return true;*/
  1734. if (Export.Visibility != Visibility.Collapsed)
  1735. return true;
  1736. return false;
  1737. }
  1738. public Button AddButton(string? caption, BitmapImage? image, string? tooltip, DynamicGridButtonClickEvent action, DynamicGridButtonPosition position = DynamicGridButtonPosition.Left)
  1739. {
  1740. var button = CreateButton(image, caption, tooltip);
  1741. button.Margin = position == DynamicGridButtonPosition.Right
  1742. ? new Thickness(2, 2, 0, 0)
  1743. : bFirstButtonAdded && AnyButtonsVisible()
  1744. ? new Thickness(0, 2, 0, 0)
  1745. : new Thickness(0, 2, 2, 0);
  1746. button.Padding = !String.IsNullOrWhiteSpace(caption) ? new Thickness(5, 1, 5, 1) : new Thickness(1);
  1747. button.Tag = action;
  1748. button.Click += Button_Click;
  1749. if (position == DynamicGridButtonPosition.Right)
  1750. RightButtonStack.Children.Add(button);
  1751. else
  1752. LeftButtonStack.Children.Add(button);
  1753. bFirstButtonAdded = false;
  1754. return button;
  1755. }
  1756. public Button AddButton(string? caption, BitmapImage? image, DynamicGridButtonClickEvent action, DynamicGridButtonPosition position = DynamicGridButtonPosition.Left)
  1757. {
  1758. var result = AddButton(caption, image, null, action, position);
  1759. return result;
  1760. }
  1761. private void Button_Click(object sender, RoutedEventArgs e)
  1762. {
  1763. var button = (Button)sender;
  1764. var action = (DynamicGridButtonClickEvent)button.Tag;
  1765. //CoreRow row = (CurrentRow > -1) && (CurrentRow < Data.Rows.Count) ? Data.Rows[this.CurrentRow] : null;
  1766. if (action.Invoke(button, SelectedRows))
  1767. Refresh(false, true);
  1768. }
  1769. #endregion
  1770. #region Header Actions
  1771. private void SelectColumnsClick()
  1772. {
  1773. var editor = new DynamicGridColumnsEditor(typeof(T));
  1774. editor.DirectEdit = IsDirectEditMode();
  1775. editor.Columns.AddRange(VisibleColumns);
  1776. if (editor.ShowDialog().Equals(true))
  1777. {
  1778. VisibleColumns.Clear();
  1779. VisibleColumns.AddRange(editor.Columns);
  1780. SaveColumns(VisibleColumns);
  1781. //OnSaveColumns?.Invoke(this, editor.Columns);
  1782. Refresh(true, true);
  1783. }
  1784. }
  1785. #endregion
  1786. #region Drag + Drop
  1787. /// <summary>
  1788. /// Handle a number of rows from a different <see cref="DynamicGrid{T}"/> being dragged into this one.
  1789. /// </summary>
  1790. /// <param name="entity">The type of entity that that the rows of <paramref name="table"/> represent.</param>
  1791. /// <param name="table">The data being dragged.</param>
  1792. /// <param name="e"></param>
  1793. protected virtual void OnDragEnd(Type entity, CoreTable table, DragEventArgs e)
  1794. {
  1795. Logger.Send(LogType.Information,"","OnDragEnd");
  1796. }
  1797. /// <summary>
  1798. /// Handle all types of items being dragged onto this grid that aren't handled by <see cref="OnDragEnd(Type, CoreTable, DragEventArgs)"/>,
  1799. /// i.e., data which is not a <see cref="CoreTable"/> from another <see cref="DynamicGrid{T}"/>
  1800. /// </summary>
  1801. /// <remarks>
  1802. /// Can be used to handle files, for example.
  1803. /// </remarks>
  1804. /// <param name="sender"></param>
  1805. /// <param name="e"></param>
  1806. protected virtual void HandleDragDrop(object sender, DragEventArgs e)
  1807. {
  1808. }
  1809. protected virtual void HandleDragOver(object sender, DragEventArgs e)
  1810. {
  1811. }
  1812. protected DragDropEffects DragTable(Type entity, CoreTable table)
  1813. {
  1814. Logger.Send(LogType.Information, "", "DragTable");
  1815. var data = new DataObject();
  1816. data.SetData(DynamicGridUtils.DragFormat, new DynamicGridDragFormat(table.ToDataTable(), entity));
  1817. var effect = DragDrop.DoDragDrop(this, data, DragDropEffects.All);
  1818. return effect;
  1819. }
  1820. protected virtual DragDropEffects OnRowsDragStart(CoreRow[] rows)
  1821. {
  1822. Logger.Send(LogType.Information, "", "OnRowsDragStart");
  1823. var table = new CoreTable();
  1824. table.LoadColumns(Data.Columns);
  1825. table.LoadRows(rows);
  1826. return DragTable(typeof(T), table);
  1827. }
  1828. #endregion
  1829. }
  1830. #region Styling
  1831. public class DynamicGridRowStyle : DynamicGridStyle<VirtualizingCellsControl>
  1832. {
  1833. public DynamicGridRowStyle() : base(null)
  1834. {
  1835. }
  1836. public DynamicGridRowStyle(IDynamicGridStyle source) : base(source)
  1837. {
  1838. }
  1839. public override DependencyProperty FontSizeProperty => Control.FontSizeProperty;
  1840. public override DependencyProperty FontStyleProperty => Control.FontStyleProperty;
  1841. public override DependencyProperty FontWeightProperty => Control.FontWeightProperty;
  1842. public override DependencyProperty BackgroundProperty => Control.BackgroundProperty;
  1843. public override DependencyProperty ForegroundProperty => Control.ForegroundProperty;
  1844. }
  1845. public class DynamicGridCellStyle : DynamicGridStyle<Control>
  1846. {
  1847. public DynamicGridCellStyle() : base(null)
  1848. {
  1849. }
  1850. public DynamicGridCellStyle(IDynamicGridStyle source) : base(source)
  1851. {
  1852. }
  1853. public override DependencyProperty FontSizeProperty => Control.FontSizeProperty;
  1854. public override DependencyProperty FontStyleProperty => Control.FontStyleProperty;
  1855. public override DependencyProperty FontWeightProperty => Control.FontWeightProperty;
  1856. public override DependencyProperty BackgroundProperty => Control.BackgroundProperty;
  1857. public override DependencyProperty ForegroundProperty => Control.ForegroundProperty;
  1858. }
  1859. public class GridSelectionControllerExt : GridSelectionController
  1860. {
  1861. public GridSelectionControllerExt(SfDataGrid datagrid)
  1862. : base(datagrid)
  1863. {
  1864. }
  1865. protected override void ProcessSelectedItemChanged(SelectionPropertyChangedHandlerArgs handle)
  1866. {
  1867. base.ProcessSelectedItemChanged(handle);
  1868. if (handle.NewValue != null)
  1869. {
  1870. //this.DataGrid.ScrollInView(this.CurrentCellManager.CurrentRowColumnIndex);
  1871. //int rowIndex = this.CurrentCellManager.CurrentRowColumnIndex.RowIndex;
  1872. var columnIndex = CurrentCellManager.CurrentRowColumnIndex.ColumnIndex;
  1873. var scrollRowIndex = DataGrid.GetVisualContainer().ScrollRows.LastBodyVisibleLineIndex;
  1874. DataGrid.ScrollInView(new RowColumnIndex(scrollRowIndex, columnIndex));
  1875. }
  1876. }
  1877. }
  1878. // Used to render boolean columns (the default "false" value shows what appears to be an intermediate state, which is ugly
  1879. // This should show nothing for false, and a tick in a box for true
  1880. public class BoolToImageConverter : AbstractConverter<bool,ImageSource>
  1881. {
  1882. public ImageSource TrueValue { get; set; }
  1883. public ImageSource FalseValue { get; set; }
  1884. public BoolToImageConverter()
  1885. {
  1886. TrueValue = Wpf.Resources.Bullet_Tick.AsBitmapImage();
  1887. }
  1888. public override ImageSource Convert(bool value)
  1889. {
  1890. return value ? TrueValue : FalseValue;
  1891. }
  1892. public override bool Deconvert(ImageSource value)
  1893. {
  1894. return ImageUtils.IsEqual(value as BitmapImage,TrueValue as BitmapImage);
  1895. }
  1896. }
  1897. public class StringToColorImageConverter : IValueConverter
  1898. {
  1899. private readonly int _height = 50;
  1900. private readonly int _width = 25;
  1901. private readonly Dictionary<string, BitmapImage> cache = new();
  1902. public StringToColorImageConverter(int width, int height)
  1903. {
  1904. _width = width;
  1905. _height = height;
  1906. }
  1907. public object? Convert(object value, Type targetType, object parameter, CultureInfo culture)
  1908. {
  1909. var str = value?.ToString();
  1910. if (str is null)
  1911. return null;
  1912. var colorcode = str.TrimStart('#');
  1913. if (!cache.ContainsKey(colorcode))
  1914. {
  1915. var col = ImageUtils.StringToColor(colorcode);
  1916. var bmp = ImageUtils.BitmapFromColor(col, _width, _height, Color.Black);
  1917. cache[colorcode] = bmp.AsBitmapImage();
  1918. }
  1919. var result = cache[colorcode];
  1920. return result;
  1921. }
  1922. public object? ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
  1923. {
  1924. return null;
  1925. }
  1926. }
  1927. public class StringArrayConverter : IValueConverter
  1928. {
  1929. object? IValueConverter.Convert(object value, Type targetType, object parameter, CultureInfo culture)
  1930. {
  1931. if (value is string[] strArray)
  1932. {
  1933. return string.Join("\n", strArray);
  1934. }
  1935. Logger.Send(LogType.Error, "", $"Attempt to convert an object which is not a string array: {value}.");
  1936. return null;
  1937. }
  1938. object IValueConverter.ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
  1939. {
  1940. return value;
  1941. }
  1942. }
  1943. #endregion
  1944. [Serializable]
  1945. class DynamicGridDragFormat
  1946. {
  1947. private string entity;
  1948. public DataTable Table { get; set; }
  1949. public Type Entity { get => CoreUtils.GetEntity(entity); set => entity = value.EntityName(); }
  1950. public DynamicGridDragFormat(DataTable table, Type entity)
  1951. {
  1952. Table = table;
  1953. Entity = entity;
  1954. }
  1955. }