DynamicGrid.cs 83 KB

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