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