DynamicGrid.cs 76 KB

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