DynamicGrid.cs 76 KB

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