DynamicGrid.cs 84 KB

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